【问题标题】:cocoon :has_many :through relationship - create new - not just "add existing"茧:has_many:通过关系 - 创建新的 - 不仅仅是“添加现有”
【发布时间】:2013-07-15 21:13:51
【问题描述】:

我正在开发一个食谱应用程序,其中食谱具有标题、描述、说明和数量的成分

我有一个配方模型、一个数量模型和一个成分模型:

class Recipe < ActiveRecord::Base
  attr_accessible :description, 
    :instructions, 
    :title, 
    :quantities_attributes, 
    :ingredients_attributes

  has_many :quantities
  has_many :ingredients, :through => :quantities

  accepts_nested_attributes_for :quantities,
    :reject_if => :all_blank,
    :allow_destroy => true
  accepts_nested_attributes_for :ingredients
end

class Quantity < ActiveRecord::Base
  attr_accessible :amount, 
    :ingredient_id,
    :ingredient_attributes

  belongs_to :recipe
  belongs_to :ingredient

  accepts_nested_attributes_for :ingredient,
    :reject_if => :all_blank
end

class Ingredient < ActiveRecord::Base
  attr_accessible :name, 
    :ingredient_id

  has_many :quantities
  has_many :recipes, through: :quantities
end

我正在使用带有简单表单的 cocoon 来创建嵌套模型表单,这是我目前所拥有的:

食谱/_form.html.haml

= f.simple_fields_for :quantities do |q|
    = render 'quantity_fields', :f => q
        = link_to_add_association 'add ingredient', f, :quantities
= f.submit

食谱/_quantity_fields.html.haml

    = f.input :amount
    = f.association :ingredient, :collection => Ingredient.all(:order => 'name'), :prompt => 'Choose an existing ingredient'
    = link_to_remove_association "remove ingredient", f

食谱/_ingredient_fields.html.haml

= f.input :name, :hint => 'New Ingredient'

这是在我的食谱中添加新成分时得到的结果:https://www.evernote.com/shard/s1/sh/3790e23d-5699-4683-8404-120515affba1/858deb9a56112d179c37d39e61ba0f6d

现在我想知道如何添加以前从未添加过的全新成分 - 您有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails-3.2 simple-form has-many-through cocoon-gem


    【解决方案1】:

    只需添加 link_to_add_association 标签

    食谱/_quantity_fields.html.haml

    .nested-fields
        = f.input :amount
        = f.association :ingredient, :collection => Ingredient.all(:order => 'name'), :prompt => 'Choose an existing ingredient'
        = link_to_remove_association "remove ingredient", f
        %br
        = link_to_add_association 'or create a new ingredient', f, :ingredient
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2021-09-24
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多