【发布时间】:2012-01-21 13:44:50
【问题描述】:
我正在尝试为食谱创建一个 Rails 应用程序,但对如何创建视图表单和控制器逻辑感到困惑。我有 2 个模型,Recipe 和 Item,加入了 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"]
但是,我不明白如何创建新的食谱视图,以便我可以在一页中直接将配料添加到食谱中。我需要使用fields_for 还是嵌套属性?如何构建视图表单和控制器逻辑以在一个页面中创建带有成分的食谱?
我在 Rails 3.1.3 上。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 views associations has-many-through