我正在开发一个食谱应用程序,其中食谱具有标题、描述、说明和数量的成分
我有一个配方模型、一个数量模型和一个成分模型:
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
现在我想知道如何添加一种以前从未添加过的全新成分 - 你有什么想法吗?