【发布时间】:2012-01-21 22:10:00
【问题描述】:
我正在尝试通过加入 Rails 3(使用 Formtastic)来实现 has_many :但我有点卡住了。我的模型设置如下:
型号:
class Project < ActiveRecord::Base
has_many :employees, :through => :teams
has_many :teams
class Employee < ActiveRecord::Base
has_many :projects, :through => :teams
has_many :teams
class Team < ActiveRecord::Base
belongs_to :project
belongs_to :employee
这一行在项目视图中为我提供了一个多选框,允许选择员工:
查看:
<%= f.input :employees, :as => :select %>
到目前为止,这已经完成了工作,但我希望有一个单独的下拉框来选择每个员工的姓名,然后选择他们在项目中的角色。我想不出让我到达那里的表单代码...
编辑:
正如建议的那样,我已经从Railscast 197: Nested Model Forms 那里得到了代码,它已经完成了。这就是我的观点:
<%= f.semantic_fields_for :employees do |builder| %>
<%= render 'employee_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "add employee", f, :employees %>
和“employee_fields”部分:
<p class="fields">
<%= f.input :name, :as => :select, :collection => Employee.find(:all) %>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
但是现在这会创建一个新员工而不是一个新团队(项目员工加入记录),所以我认为它充当has_many 而不是has_many :through。如何编辑它,以便上面的 :name 输入将记录添加到 project[employee_ids][]?
【问题讨论】:
-
railscasts.com 的嵌套模型表单集(编号 196 和 197)可能会提供一些想法。它们并非专门针对
has_many :through,但它们确实提供了为父对象拥有多个子字段的能力。 -
我昨晚刚看了那些!我得到了这个功能,但我仍然坚持
has_many :through部分。
标签: ruby-on-rails has-many-through formtastic