title: How to display unique records from a has_many through relationship?
body: <p>I'm wondering what is the best way to display unique records from a has_many, through relationship in Rails3.</p>
  
  <p>I have three models:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
      has_many :orders
      has_many :products, :through =&gt; :orders
  end
  
  class Products &lt; ActiveRecord::Base
      has_many :orders
      has_many :users, :through =&gt; :orders
  end
  
  class Order &lt; ActiveRecord::Base
      belongs_to :user, :counter_cache =&gt; true 
      belongs_to :product, :counter_cache =&gt; true 
  end
  </code></pre>
  
  <p>Lets say I want to list all the products a customer has ordered on their show page. </p>
  
  <p>They may have ordered some products multiple times, so I'm using counter_cache to display in descending rank order, based on the number of orders.</p>
  
  <p>But, if they have ordered a product multiple times, I need to ensure that each product is only listed once.</p>
  
  <pre><code>@products = @user.products.ranked(:limit =&gt; 10).uniq!
  </code></pre>
  
  <p>works when there are multiple order records for a product, but generates an error if a product has only been ordered once. (ranked is custom sort function defined elsewhere)</p>
  
  <p>Another alternative is:</p>
  
  <pre><code>@products = @user.products.ranked(:limit =&gt; 10, :select =&gt; "DISTINCT(ID)")
  </code></pre>
  
  <p>I'm not confident that I'm on the right approach here. </p>
  
  <p>Has anyone else tackled this? What issues did you come up against? Where can I find out more about the difference between .unique! and DISTINCT()? </p>
  
  <p>What is the best way to generate a list of unique records through a has_many, through relationship?</p>
  
  <p>Thanks</p>