加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 带有has_many的Rails复杂视图表单:通过关联

发布时间:2020-12-17 03:53:29 所属栏目:百科 来源:网络整理
导读:我正在尝试为食谱创建一个rails应用程序,但我对如何创建视图表单和控制器逻辑感到困惑.我有2个模型,配方和项目,加入了has_many:通过与Ingredient模型的关联,如下所示: class Recipe ActiveRecord::Base has_many :ingredients has_many :items,:through =
我正在尝试为食谱创建一个rails应用程序,但我对如何创建视图表单和控制器逻辑感到困惑.我有2个模型,配方和项目,加入了has_many:通过与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

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

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上.

解决方法

accepted_nested_attributes_for-method正是您要寻找的.
Ryan Bates在它上面做了很好的 Railscast.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读