cocoon:has_many:通过关系 - 创建新 - 不只是“添加现有”

时间:2013-07-17 10:46:51

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

我正在制作配方应用程序,其中配方具有标题,描述,说明和数量的成分

我有食谱模型,数量模型和成分模型:

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

现在我想知道如何添加一种以前没有添加的全新成分 - 你有什么想法吗?

1 个答案:

答案 0 :(得分:0)

只需添加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