【问题标题】:Nested Object Forms not working as expected嵌套对象表单未按预期工作
【发布时间】:2010-05-23 23:02:29
【问题描述】:

我正在尝试使 nested model forms 视图正常工作。据我所知,我做的一切都是正确的,但它仍然无法正常工作。

我正在使用 Rails 3 beta 3。

我的模型符合预期:

class Recipe < ActiveRecord::Base
  has_many :ingredients, :dependent => :destroy
  accepts_nested_attributes_for :ingredients
  attr_accessible :name
end
class Ingredient < ActiveRecord::Base
  attr_accessible :name, :sort_order, :amount
  belongs_to :recipe  
end

我可以按预期使用 Recipe.ingredients_attributes=:

recipe = Recipe.new
recipe.ingredients_attributes = [ {:name=>"flour", :amount=>"1 cup"}, {:name=>"sugar", :amount=>"2 cups"}]
recipe.ingredients.size    # -> 2; ingredients contains expected instances

但是,我无法使用参数as shown in the documentation 的散列创建新的对象图:

params = { :name => "test", :ingredients_attributes => [ {:name=>"flour", :amount=>"1 cup"}, {:name=>"sugar", :amount=>"2 cups"}] }
recipe = Recipe.new(params)
recipe.name    # -> "test"
recipe.ingredients    # -> []; no ingredient instances in the collection

我在这里做错了吗?还是 Rails 3 beta 有问题?

更新

这是由配方中的attr_accessible :name 引起的错误。这不是 Rails3 特有的。

【问题讨论】:

    标签: ruby-on-rails ruby forms nested


    【解决方案1】:

    你试过保存记录但仍然没有得到任何成分吗?从你上面的例子看,没有保存,所以我不相信食谱有任何成分。

    针对您在下面的回答,我相信您可以将ingredients_attributes 添加为attr_accessible。

    【讨论】:

    • 我确实尝试过保存和不保存,但都没有效果。
    【解决方案2】:

    我找到了答案:配方中attr_accessible :name 的存在将破坏成分属性(从而破坏嵌套模型形式)。删除它,一切正常。我已经证实这个错误至少早在 Rails 2.3.2 就存在。

    关闭提交bug report...

    【讨论】:

      【解决方案3】:

      我已经确认它不是 Rails 3 错误;我在 2.3 和 3.0 中都构建了Railscast example,它在这两种情况下都像宣传的那样工作。这意味着它与我的代码有关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-03
        • 2019-05-24
        • 1970-01-01
        相关资源
        最近更新 更多