E
E
exploitvn2014-02-06 01:15:11
Ruby on Rails
exploitvn, 2014-02-06 01:15:11

What could be the causes of NoMethodError when validating a collection_select field that refers to another model?

There is a SubClass model with field validation:

belongs_to :func_class 
  validates :func_class_id, presence: true
  validates :title, presence: { message: "Заголовок не должен быть пустым" }
  validates :title, length: { in: 3..500, message: "Длина Заголовка должна быть от 3 до 500 символов" }

There is a controller SubClassesController with declared variables:
def new
    @sub_class = SubClass.new
    @func_class_all = FuncClass.all
  end

And the form itself _form.html.erb
<%= form_for(@fire_sub_class) do |f| %>
.....
<div class="field">
      Title:<br>
      <%= f.text_field :title %>
    </div>    
    <div class="field">
      Func class:<br>
      <%= f.collection_select(:func_class_id, @func_class_all, :id, :title) %>
    </div>
.....

When filling out the form with invalid values ​​(for example, an empty title), this NoMethodError
"undefined method `map' for nil:NilClass" exception occurs instead of the messages specified during validation (message property). Moreover, it refers to the line with the collection_select element in _form.html.erb
The FuncClass table itself is naturally not empty. The FuncClass model is also quite simple, with a couple of text fields.
has_many :sub_class, dependent: :destroy
  validates :title, presence: { message: "Заголовок не должен быть пустым" }
  validates :title, length: { in: 3..254, message: "Длина Заголовка должна быть от 3 до 254 символов" }
  validates :title, uniqueness: { message: "Заголовок должен быть уникальным!" }

Here is an example call:
Parameters:
{"utf8"=>"✓",
 "authenticity_token"=>"iXBbWvvPlsIYqby0lKEJYTsUAaMl1T54tKFumDmRAWE=",
 "sub_class"=>{"title"=>"",
 "func_class_id"=>"1"},
 "commit"=>"OK"}

In the FuncClass model, the validation is successful, and in case of erroneously entered data, as expected, the message I specified in the model appears (the message property).
Software versions used:
ruby ​​2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]
Rails 4.0.2
Thanks in advance for any helpful information.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shetani, 2014-02-07
@Shetani

The exception says that the variable f is nil and belongs to the NilClass class, which does not have a map method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question