title: Rails has_many through, grouping and summing data
body: <p>I'm confused about how to group and obtain data with a has_many through relationship.  My current models look like the following:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
     has_many :project_items, dependent: :destroy
     has_many :ingredients, through: :project_items
  end
  
  class Ingredient &lt; ActiveRecord::Base
     has_many :project_items
  end
  
  class ProjectItem
     belongs_to :user
     belongs_to :ingredient
  end
  </code></pre>
  
  <p>This allows me to call the following from my view:</p>
  
  <pre><code>&lt;%= render partial: "users/project_item", collection: @project_items, as: :ingredient %&gt;
  </code></pre>
  
  <p>with @project_items being defined in my controller as:</p>
  
  <pre><code>@project_items = @user.ingredients
  </code></pre>
  
  <p>which directs to a _project_item partial that currently just outputs name and quantity and when it was created.</p>
  
  <pre><code>&lt;li&gt;
      &lt;span class="span2"&gt;&lt;%= ingredient.name %&gt;&lt;/span&gt;
      &lt;span class="span2"&gt;&lt;%= ingredient.quantity %&gt;&lt;/span&gt;
      &lt;span class="span3"&gt;&lt;%= @user.pantry_items.find_by(:ingredient_id =&gt; ingredient.id).created_at %&gt;&lt;/span&gt;
  &lt;/li&gt;
  </code></pre>
  
  <p>This works well and outputs all the correct data.  However, the database has multiple instances of the same ingredient from different projects.  I'm looking to do the following</p>
  
  <p><strong>1. Group by name with only the same name listed once</strong></p>
  
  <p>If I use <code>@user.ingredients.group_by(&amp;:name)</code> I get no results returned.  If I use `@user.ingredients.group('name') I get the following call:</p>
  
  <pre><code>: SELECT "ingredients".* FROM "ingredients" INNER JOIN "project_items" ON "ingredients"."id" = "project_items"."ingredient_id" WHERE "project_items"."user_id" = $1 GROUP BY name
  </code></pre>
  
  <p>But gives an error on the render as: <em>PG::Error: ERROR:  column "ingredients.id" must appear in the GROUP BY clause or be used in an aggregate function</em></p>
  
  <p><strong>2. Is it possible to add and return a column of a grouped result?</strong> For example I have:</p>
  
  <pre><code>Name            Quantity
  
  Oak 2x2             2
  
  Oak 2x2             4
  </code></pre>
  
  <p>To return  Oak 2x2   6?  </p>
  
  <p>I'm guessing it would look like <code>@user.ingredients.select('ingredients, sum(quantity) )</code> but I'm not sure how to include it with the grouping and have it output correctly with my view.</p>