2010-01-20 113 views
0

我有一個房間模型和一個人模型。accepted_nested_attributes_for並選擇標記

房間可以有很多人,一個人可以有一個房間。

在房間創建畫面,我可以「鏈接」 N人到這個新的房間 所以我想有選擇的標籤數量可變的,其中包含所有的人的名單

我不知道該怎麼建立選擇標籤。

誰能幫助

感謝...

我有以下關聯

class Room < ActiveRecord::Base 
    has_many :people 
    accepts_nested_attributes_for :people 
end 

class Person < ActiveRecord::Base 
    belongs_to :room 
end 

我使用的部分來構建房間/新形式

<% 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 %> 

回答

2

尼斯...並快速回答謝謝!

這裏是測試代碼是正確的

<% 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 %> 
2

看看ActionView::Helpers::FormOptionsHelper模塊。它提供了collection_select方法。

這部分做了你在找什麼:

<% 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 %>