How to display unique records from a has_many through relationship?

Have you tried to specify the :uniq option on the has_many association:

has_many :products, :through => :orders, :uniq => true

From the Rails documentation:

:uniq

If true, duplicates will be omitted from the collection. Useful in conjunction with :through.

UPDATE FOR RAILS 4:

In Rails 4, has_many :products, :through => :orders, :uniq => true is deprecated. Instead, you should now write has_many :products, -> { distinct }, through: :orders. See the distinct section for has_many: :through relationships on the ActiveRecord Associations documentation for more information. Thanks to Kurt Mueller for pointing this out in his comment.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)