我正在创建一个注册,其中我有“Person”“Child”和“Meal”模型。一个人可以有很多孩子,可以为自己注册很多餐点,也可以为孩子们注册很多餐点。
关键是餐点只属于个人(没有必要将它们分配给孩子们),所以我有一个表单中的餐点创作部分,还有另一个孩子们的创作部分。
当我提交表单时,我在 Person 的控制器中收到Can't mass-assign protected attributes: foods错误。
问题是,如何在 Children fields_for 部分下创建 Meals 实例而不会出现此错误并且不会在 Meals 和 Children 之间建立连接?
这是我的人模型
class Person < ActiveRecord::Base
has_many :meals
has_many :registrations, :dependent => :destroy
has_many :programs, :through => :registrations
has_many :children
attr_accessible :email_address, :first_name, :home_country, :payment, :phone_number, :price_category, :price_method, :reference_number, :second_name, :meals_attributes, :registrations_attributes, :children_attributes
validate :first_name, :second_name, :home_country, :email_address, :payment, :price_method, :presence => true
accepts_nested_attributes_for :meals, :allow_destroy => true, :reject_if => proc { |attributes| attributes['meal_type'].blank? }
accepts_nested_attributes_for :registrations, :allow_destroy => true
accepts_nested_attributes_for :children, :allow_destroy => true
我的膳食模型
class Meal < ActiveRecord::Base
attr_accessible :food_type, :meal_date, :meal_type, :person_id, :meal_id
validate :food_type, :meal_date, :meal_type, :presence => true
belongs_to :person
end
我的 Person 控制器的新部分
def new
@person = Person.new
meal = @person.meals.build
@meal_dates = ["2013-07-09","2013-07-10","2013-07-11","2013-07-12","2013-07-13","2013-07-14"]
registration = @person.registrations.build
child = @person.children.build
@programs = Program.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @person }
end
这是主要 _form 中的子部分
<h2>Children</h2>
<%= f.fields_for :children do |builder| %>
<%= render "child_fields", :f => builder %>
<% end %>
<%= link_to_add_fields 'Add Children', f, :children %>
和孩子一起吃饭
<fieldset>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :age %><br />
<%= f.number_field :age %>
</div>
<div class="field">
<%= f.label :language %><br />
<%= f.text_field :language %>
</div>
<div class="field">
<%= f.label :child_care %><br />
<%= f.check_box :child_care %>
</div>
<h3>Child's meals</h3>
<table>
<tr>
<th>Date</th>
<th>Food type</th>
<th>Meal type</th>
</tr>
<% @meal_dates.each do |meal_date| %>
<%= f.fields_for :meals do |f3| %>
<tr>
<td><%= f3.text_field :meal_date, :value => meal_date %></td>
<td><%= f3.hidden_field :food_type, :class => 'FoodType', :value => 'vegetarian'%></td>
<td><%= f3.select(:meal_type, [['Lunch', 1], ['Three Meals', 3], ['None', nil]]) %></td>
</tr>
<% end %>
<% end %>
</table>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
你可以在我的 github 中找到完整的代码:https ://github.com/szabcsee/brk2013