Problems validating form with collection_select


#1

I have the following models:

class Comandancia < ActiveRecord::Base
has_many :elementos
end

class Elemento < ActiveRecord::Base
belongs_to :comandancia
validates_presence_of :nombre, :apellido_paterno, :apellido_materno,
:comandancia
end

In the view for New Elemento I’m using
<%= start_form_tag :action => ‘create’ %>
<%= render :partial => ‘form’ %>
<%= collection_select(‘elemento’, ‘comandancia_id’, @comandancia,
‘id’,
‘nombre’)%>
<%= submit_tag “Create” %>
<%= end_form_tag %>

When I create a New Elemento and provide values for all the required
fields,
everything is OK, the collection_select works just fine and stores the
proper value in the Elemento table.

BUT, when I don’t provide one of the required fields so that the model
doesn’t validate, I get the following error:

Showing app/views/adminelemento/new.rhtml where line #5 raised:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.inject

And it points the error to the collection_select line in new.rhtml. Why
collection_select becomes a problem if the validation is failing because
of
the OTHER fields?? How can I avoid this error?

My _form.rhtml is as follows:
<%= error_messages_for ‘elemento’ %>

Nombre
<%= text_field 'elemento', 'nombre' %>

Apellido paterno
<%= text_field 'elemento', 'apellido_paterno' %>

Apellido materno
<%= text_field 'elemento', 'apellido_materno' %>

Direccion
<%= text_area 'elemento', 'direccion' %>

Sorry of this post is too long but this is puzzling me.