我正在尝试为食谱创建一个 Rails 应用程序,但对如何创建 View 表单和 Controller 逻辑感到困惑。我有 2 个模型,Recipe 和 Item,加入了与 Ingredient 模型的 has_many :through
关联,如下所示:
class Recipe < ActiveRecord::Base
has_many :ingredients
has_many :items, :through => :ingredients
end
class Item < ActiveRecord::Base
has_many :ingredients
has_many :recipes, :through => :ingredients
end
class Ingredient < ActiveRecord::Base
# Has extra attribute :quantity
belongs_to :recipe
belongs_to :item
end
此关联在控制台中起作用。例如:
Recipe.create( :name => 'Quick Salmon' )
Item.create( :name => 'salmon', :unit => 'cups' )
Ingredient.create( :recipe_id => 1, :item_id => 1, :quantity => 3)
Recipe.first.ingredients
=> [#<Ingredient id: 1, recipe_id: 1, item_id: 1, quantity: 3]
Recipe.first.items
=> [#<Item id: 1, name: "salmon", unit: "cups"]
但是,我不明白如何创建新的菜谱 View ,以便我可以将配料直接添加到一页中的菜谱中。我需要使用 fields_for
或嵌套属性吗?如何构建 View 表单和 Controller 逻辑以在一页中创建包含成分的菜谱?
我使用的是 Rails 3.1.3。
最佳答案
accepts_nested_attributes_for
-方法就是您正在寻找的。
Ryan Bates 做得非常出色 Railscast就在上面。
关于ruby-on-rails - Rails 复杂 View 表单与 has_many :through association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527271/