ruby-on-rails - Rails 复杂 View 表单与 has_many :through association

标签 ruby-on-rails ruby-on-rails-3 view associations has-many-through

我正在尝试为食谱创建一个 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就在上面。

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

关于ruby-on-rails - Rails 复杂 View 表单与 has_many :through association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527271/

相关文章:

ruby-on-rails - 列出所有 paper_trail 版本(包括关联)的正确方法是什么?

ruby-on-rails - 使用 Rack Cache 时如何跟踪 API 请求数

javascript - 为什么 Rails 默认不在 HTML 页面底部包含 Javascript 文件?

ruby-on-rails - 验证自定义单词

在 GameMaker 中查看大小 : Studio dependent on first room

ruby-on-rails - 工厂女孩 : How do define a factory without passing parameters

ruby-on-rails - 与 Rails 3.2 和 SASS 一起使用的 CSS 问题

ruby-on-rails - 如何正确翻译回形针错误消息?

c# - 从 View 模型 (WPF) 调用 View 中的动画

ios - 我如何检查我的 View Controller 现在是否显示?