【问题标题】:Rails complex view form with has_many :through association带有has_many的Rails复杂视图表单:通过关联
【发布时间】: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


    【解决方案1】:

    accepts_nested_attributes_for-方法是您正在寻找的。 瑞安·贝茨(Ryan Bates)在上面写了一个出色的Railscast

    您还应该检查documentation for Active Record Nested Attributes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 2012-02-01
      • 2017-08-09
      • 1970-01-01
      相关资源
      最近更新 更多