【发布时间】:2012-11-09 02:26:39
【问题描述】:
食谱和成分之间存在多对多关系。我正在尝试构建一个表单,让我可以将成分添加到食谱中。
(这个问题的变体已经被反复问过,我已经花了几个小时来解决这个问题,但我对 accepts_nested_attributes_for 所做的事情从根本上感到困惑。)
在您被下面的所有代码吓到之前,我希望您会明白这确实是一个基本问题。以下是不可怕的细节......
错误
当我显示一个创建配方的表单时,我收到错误“未初始化的常量配方::IngredientsRecipe”,指向我的表单部分中的一行
18: <%= f.fields_for :ingredients do |i| %>
如果我将这一行改为“成分”单数
<%= f.fields_for :ingredient do |i| %>
然后显示表单,但是当我保存时,我收到一个批量分配错误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
控制器
作为rails generate scaffold生成的RESTful资源
而且,因为“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 %>
环境
- Rails 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])
所以传递的参数,包括嵌套属性,在某些方面是不正确的。但是我已经尝试了很多变体,它们可以修复一个又一个。我不明白什么?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord nested-attributes has-many-through