Note that there are some explanatory texts on larger screens.

plurals
  1. POcocoon :has_many :through relationship - create new - not just "add existing"
    text
    copied!<p>I am working on a recipe application where a recipe has a title, description, instructions and ingredients with quantities</p> <p>I'm having a recipe model, a quantity model and an ingredient model:</p> <pre><code>class Recipe &lt; ActiveRecord::Base attr_accessible :description, :instructions, :title, :quantities_attributes, :ingredients_attributes has_many :quantities has_many :ingredients, :through =&gt; :quantities accepts_nested_attributes_for :quantities, :reject_if =&gt; :all_blank, :allow_destroy =&gt; true accepts_nested_attributes_for :ingredients end class Quantity &lt; ActiveRecord::Base attr_accessible :amount, :ingredient_id, :ingredient_attributes belongs_to :recipe belongs_to :ingredient accepts_nested_attributes_for :ingredient, :reject_if =&gt; :all_blank end class Ingredient &lt; ActiveRecord::Base attr_accessible :name, :ingredient_id has_many :quantities has_many :recipes, through: :quantities end </code></pre> <p>I am using cocoon with simple form to create a nested-model-form, here's what I have so far:</p> <p>recipes/_form.html.haml</p> <pre><code>= f.simple_fields_for :quantities do |q| = render 'quantity_fields', :f =&gt; q = link_to_add_association 'add ingredient', f, :quantities = f.submit </code></pre> <p>recipes/_quantity_fields.html.haml</p> <pre><code> = f.input :amount = f.association :ingredient, :collection =&gt; Ingredient.all(:order =&gt; 'name'), :prompt =&gt; 'Choose an existing ingredient' = link_to_remove_association "remove ingredient", f </code></pre> <p>recipes/_ingredient_fields.html.haml</p> <pre><code>= f.input :name, :hint =&gt; 'New Ingredient' </code></pre> <p>here's what I get when adding a new ingredient to my recipe: <a href="https://www.evernote.com/shard/s1/sh/3790e23d-5699-4683-8404-120515affba1/858deb9a56112d179c37d39e61ba0f6d" rel="nofollow">https://www.evernote.com/shard/s1/sh/3790e23d-5699-4683-8404-120515affba1/858deb9a56112d179c37d39e61ba0f6d</a></p> <p>Now I'm wondering how I could add a completely new ingredient which hasn't been added before - do you have any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload