0

我上的配方應用程序,其中一個配方有一個標題,描述,說明和成分與數量的工作繭:的has_many:通過關係 - 創造新的 - 不只是「添加現有」

我有一個祕方模型,數量模型和配料模型:

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 

我使用繭用簡單的形式來創建一個嵌套模型的形式,這是我到目前爲止有:

食譜/ _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

現在我想知道如何添加一種以前沒有添加過的全新成分 - 你有什麼想法嗎?

回答

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 
相關問題