accepts_nested_attributes_for and select tag
I've a Room model and a Person model.
A room can have many person and a person can have one room.
On the room creation screen I can 'link' n person to this new room So i want to have a variable amount of select tag which contains the list of all people
I don't know how to build the select tag.
Can anyone help
thanks...
I've the following associations
class Room < ActiveRecord::Base
has_many :people
accepts_nested_attributes_for :people
end
class Person < ActiveRecord:开发者_开发百科:Base
belongs_to :room
end
I use a partial to build the rooms/new form
<% form_for(@room) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :date %><br />
<%= f.date_select :date %>
</p>
<% f.fields_for :people do |builder| %>
<p>
<%= builder.label :person_id, "Person" %><br />
<%= select 'room', 'people', Person.all.collect{|person| [person.name, person.id]}%>
</p>
<% end %>
<p>
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
Have a look at the ActionView::Helpers::FormOptionsHelper module. It supplies the collection_select method.
This partial does what you're looking for:
<% form_for(@room) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :date %><br />
<%= f.date_select :date %>
</p>
<p>
<%= f.label :people_ids, "Person" %><br />
<%= collection_select :people_ids, Person.all, :name, :id, {:multiple => true} %>
</p>
<p>
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
Nice... and quick answer thanks!
here is the tested code to be correct
<% f.fields_for :people do |builder| %>
<p>
<%= builder.label :person_id, "Person" %><br />
<%= builder.collection_select :person_id, Person.all, :id, :name, {:multiple => true} %>
</p>
<% end %>
精彩评论