我在Recipes和Ingredients之间有多对多的关系。我正在尝试构建一个允许我在食谱中添加成分的表单。
(这个问题的变体已经被反复问过,我已经花了几个小时在这个问题上,但从根本上被什么弄糊涂了accepts_nested_attributes_for
。)
在你被下面的所有代码吓到之前,我希望你会明白这确实是一个基本问题。以下是不可怕的细节......
错误
当我显示一个创建配方的表单时,我收到错误“未初始化的常量配方::IngredientsRecipe”,指向我的表单部分中的一行
18: <%= f.fields_for :ingredients do |i| %>
如果我更改此行以使“成分”单数
<%= f.fields_for :ingredient do |i| %>
然后显示表单,但是当我保存时,我得到一个 mass assignment error Can't mass-assign protected attributes: ingredient
。
模型(在 3 个文件中,相应命名)
class Recipe < ActiveRecord::Base
attr_accessible :name, :ingredient_id
has_many :ingredients, :through => :ingredients_recipes
has_many :ingredients_recipes
accepts_nested_attributes_for :ingredients
accepts_nested_attributes_for :ingredients_recipes
end
class Ingredient < ActiveRecord::Base
attr_accessible :name, :recipe_id
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
accepts_nested_attributes_for :recipes
accepts_nested_attributes_for :ingredients_recipes
end
class IngredientsRecipes < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
attr_accessible :ingredient_id, :recipe_id
accepts_nested_attributes_for :recipes
accepts_nested_attributes_for :ingredients
end
控制器
作为 RESTful 资源生成的rails generate scaffold
而且,因为“recipe”的复数形式不规则,inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'recipe', 'recipes'
end
查看 ( recipes/_form.html.erb
)
<%= form_for(@recipe) do |f| %>
<div class="field">
<%= f.label :name, "Recipe" %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :ingredients do |i| %>
<div class="field">
<%= i.label :name, "Ingredient" %><br />
<%= i.collection_select :ingredient_id, Ingredient.all, :id, :name %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
环境
- 导轨 3.2.9
- 红宝石 1.9.3
尝试了一些东西
如果我更改视图f.fields_for :ingredient
然后加载表单(它找到Recipe::IngredientRecipe
正确,但是当我保存时,我收到如上所述的批量分配错误。这是日志
Started POST "/recipes" for 127.0.0.1 at 2012-11-20 16:50:37 -0500
Processing by RecipesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/fMS6ua0atk7qcXwGy7NHQtuOnJqDzoW5P3uN9oHWT4=", "recipe"=>{"name"=>"Stewed Tomatoes", "ingredient"=>{"ingredient_id"=>"1"}}, "commit"=>"Create Recipe"}
Completed 500 Internal Server Error in 2ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: ingredient):
app/controllers/recipes_controller.rb:43:in `new'
app/controllers/recipes_controller.rb:43:in `create'
控制器中的故障线很简单
@recipe = Recipe.new(params[:recipe])
所以传递的参数,包括嵌套属性,在某种程度上是不正确的。但是我已经尝试了很多变体,它们可以修复一个又一个。我不明白什么?