title: Modeling multiple associations in rails
body: <p>I'm trying to capture a data hierarchy in a rails model and am having some trouble. here is a releationship diagram: <a href="https://www.lucidchart.com/invitations/accept/5744614c-2054-4f79-a842-8118e985f840" rel="nofollow">https://www.lucidchart.com/invitations/accept/5744614c-2054-4f79-a842-8118e985f840</a></p>
  
  <p>My models are User, Recipe, RecipeIngredient, Ingredient, and Unit.</p>
  
  <ul>
  <li>Users own Recipes. A User can have zero to many Recipes. </li>
  <li>Recipes have zero to many RecipeIngredients. RecipeIngredients are
  dependents of Recipes.</li>
  <li>A RecipeIngredient points to exactly one Recipe and one Ingredient
  and one Unit. </li>
  <li>Neither Unit nor Ingredient are dependents of RecipeIngredient. </li>
  <li>Ingredients can be used in multiple RecipeIngredients.</li>
  <li>Units can be used in multiple RecipeIngredients.</li>
  </ul>
  
  <p>Here are my model definitions:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
  end
  
  class Ingredient &lt; ActiveRecord::Base
  end
  
  class Unit &lt; ActiveRecord::Base
  end
  
  class Recipe &lt; ActiveRecord::Base
      has_many :recipe_ingredients
      accepts_nested_attributes_for   :recipe_ingredients
  end
  
  class RecipeIngredient &lt; ActiveRecord::Base
    belongs_to :recipe
    belongs_to :ingredient
  end
  </code></pre>
  
  <p>I've used this in my EDIT form:</p>
  
  <pre><code>&lt;%= f.fields_for :recipe_ingredients do |recipe_ingredient| %&gt;
      &lt;%= recipe_ingredient.collection_select( :ingredient_id, Ingredient.all, :id, :name ) %&gt;
      &lt;%= recipe_ingredient.number_field :quantity, :step =&gt; 'any' %&gt;
      &lt;%= recipe_ingredient.collection_select( :unit, Unit.all, :name, :name ) %&gt;
      &lt;%= recipe_ingredient.text_field :comment %&gt;
  </code></pre>
  
  <p>When I submit the form, the Recipe is updated properly, but new RecipeIngredient rows are created (rather than updated). The Ingredient is nil in all of the new rows. I've obviously overlooked an association definition. What did I do wrong?</p>
  
  <p>Thanks!</p>