我有以下型号:
class MealPlan < ActiveRecord::Base
has_many :food_contents
has_many :foods,:through => :food_contents
accepts_nested_attributes_for :food_contents
attr_accessible :food_contents_attributes,:name
end
class Food < ActiveRecord::Base
validates_presence_of :name,:protein,:carbs,:fats,:calories
validates_numericality_of :protein,:carbs,:fats,:calories
end
class FoodContent < ActiveRecord::Base
belongs_to :meal_plan
belongs_to :food
attr_accessible :food_id, :how_much,:meal_plan_id
validates_presence_of :food,:meal_plan
end
我在膳食计划控制器中有以下代码:
def new
@meal_plan = MealPlan.new
3.times { @meal_plan.food_contents.build }
end
def create
@meal_plan = MealPlan.new(params[:meal_plan])
end
以及以下膳食计划表格:
<%= form_for(@meal_plan) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :food_contents do |b| %>
<fieldset>
<legend>New food</legend>
<%= b.collection_select :food_id,Food.all,:id,:name,{},{:class => "food_id_selector"} %><br/>
<%= b.text_field :how_much,:class => "how_much_input" %><br/>
<%= content_tag(:p,nil,:class => "food_acumulator") %>
</fieldset>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
但是,当它总是无法保存模型时,会出现错误:
> #<ActiveModel::Errors:0xb34212e8
@base=#<MealPlan id: nil, name: "Sample", created_at: nil, updated_at: nil>,
@messages={:"food_contents.meal_plan"=>["can't be blank"]}>
从我调试的内容来看,罪魁祸首validates_presence_of :meal_plan
来自:
class FoodContent < ActiveRecord::Base
...
...
validates_presence_of :food,:meal_plan
end
一方面,我可以理解为什么它不能保存嵌套模型(因为膳食计划还没有 id),但另一方面,我想确保我正在做的事情是正确的。