Rails复杂视图表单与has_many:通过关联

pan*_*ani 4 views ruby-on-rails associations has-many-through ruby-on-rails-3

我正在尝试为食谱创建一个rails应用程序,但我对如何创建视图表单和控制器逻辑感到困惑.我有2个模型,配方和项目,加入has_many :through与Ingredient模型的关联如下:

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
Run Code Online (Sandbox Code Playgroud)

此关联在控制台中有效.例如:

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"]
Run Code Online (Sandbox Code Playgroud)

但是,我不明白如何创建新的配方视图,以便我可以在一个页面中将配料直接添加到配方中.我需要使用fields_for或嵌套属性吗?如何构建视图表单和控制器逻辑以在一个页面中创建具有成分的配方?

我在Rails 3.1.3上.

kla*_*eck 10

这种accepts_nested_attributes_for方法正是你要找的.Ryan Bates 在它上面做了很好的Railscast.

您还应该查看Active Record Nested Attributes文档