I am wondering what is the best way to display unique entries from has_many, through relationships in Rails3.
I have three models:
class User < ActiveRecord::Base has_many :orders has_many :products, :through => :orders end class Products < ActiveRecord::Base has_many :orders has_many :users, :through => :orders end class Order < ActiveRecord::Base belongs_to :user, :counter_cache => true belongs_to :product, :counter_cache => true end
Suppose I want to list all the products ordered by a customer on their display page.
Perhaps they ordered several products several times, so I use counter_cache to display in descending order of rank depending on the number of orders.
But, if they ordered the product several times, I need to make sure that each product is listed only once.
@products = @user.products.ranked(:limit => 10).uniq!
works when there are several order records for a product, but generates an error if the product was ordered only once. (ranking is a custom sorting function defined elsewhere)
Another variant:
@products = @user.products.ranked(:limit => 10, :select => "DISTINCT(ID)")
I am not sure that I am here right.
Has anyone else done this? What problems have you encountered? Where can I find out more about the difference between .unique! and DISTINCT ()?
What is the best way to create a list of unique entries through has_many through relationships?
thank
ruby-on-rails ruby-on-rails-3 unique distinct
Andy Harvey May 01 '11 at 5:19 a.m. 2011-05-01 05:19
source share