Forum: Ruby on Rails Problems validating form with collection_select

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Naju Ventura (Guest)
on 2006-05-24 20:18
(Received via mailing list)
I have the following models:

class Comandancia < ActiveRecord::Base
  has_many :elementos

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

In the view for New Elemento I'm using
<%= start_form_tag :action => 'create' %>
  <%= render :partial => 'form' %>
  <%= collection_select('elemento', 'comandancia_id', @comandancia,
  <%= submit_tag "Create" %>
<%= end_form_tag %>

When I create a New Elemento and provide values for all the required
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
the OTHER fields?? How can I avoid this error?

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

<p><label for="elemento_nombre">Nombre</label><br/>
<%= text_field 'elemento', 'nombre' %></p>

<p><label for="elemento_apellido_paterno">Apellido paterno</label><br/>
<%= text_field 'elemento', 'apellido_paterno' %></p>

<p><label for="elemento_apellido_materno">Apellido materno</label><br/>
<%= text_field 'elemento', 'apellido_materno' %></p>

<p><label for="elemento_direccion">Direccion</label><br/>
<%= text_area 'elemento', 'direccion' %></p>

<!--<p><label for="elemento_comandancia_id">Id comandancia</label><br/>
<%= text_field 'elemento', 'comandancia_id' %></p> -->


Sorry of this post is too long but this is puzzling me.
This topic is locked and can not be replied to.