accepts_nested_attributes_for和select标签

时间:2010-01-20 20:34:46

标签: ruby-on-rails ruby activerecord

我有一个房间模型和一个人模型。

一个房间可以有很多人,一个人可以有一个房间。

在房间创建屏幕上,我可以将此人“链接”到这个新房间 所以我希望有一个可变数量的选择标签,其中包含所有人的列表

我不知道如何构建select标签。

任何人都可以提供帮助

感谢...

我有以下协会

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

class Person < ActiveRecord::Base
  belongs_to :room
end

我使用partial来构建房间/新表格

<% 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 个答案:

答案 0 :(得分: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 %>

答案 1 :(得分: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 %>
相关问题