Rails的复杂的视图形式的has_many:通过协会 [英] Rails complex view form with has_many :through association
问题描述
我想创建一个菜谱Rails应用程序,但很困惑如何创建视图的形式和控制器逻辑。我有2个型号,配方和项目,在的has_many加入:通过与成分模型
的关联如下:
I'm trying to create a rails app for recipes, but am confused on how to create the view forms and controller logic. I have 2 models, Recipe and Item, joined in a has_many :through
association with an Ingredient model as follows:
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
本协会工作在控制台。例如:
This association works in the console. For example:
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
或嵌套属性?如何构建视图的形式和控制器逻辑创建配方,具有配料,在一个页面?
However, I don't understand how to create the new recipe view so that I can add ingredients directly to a recipe in one page. Do I need to use fields_for
or nested attributes? How do I build the view form and controller logic to create a recipe, with ingredients, in one page?
我on Rails的3.1.3。
I'm on Rails 3.1.3.
推荐答案
的 accepts_nested_attributes_for
-method是你在找什么。
瑞安贝茨做了一个很好的 Railscast 就可以了。
The accepts_nested_attributes_for
-method is what you are looking for.
Ryan Bates has done an excellent Railscast on it.
您也应该检查<一个href=\"http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html\">documentation对于Active Record的嵌套属性
这篇关于Rails的复杂的视图形式的has_many:通过协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!