1

I have two models: Products and Tags through a products_tags join in a HABTM relationship.

I am currently defining my controller index as:

@stats = Product.all(:include => :tags).uniq

which returns an array. How can I return an Active Rel object? I tried added scoped, however received a no method error.

I need to find and list a unique list of tags, and be able to view what product each specif tag belongs to.

Yogzzz
  • 2,735
  • 5
  • 36
  • 56

1 Answers1

1

Try @stats = Product.includes(:tags).uniq.

Note that uniq turns the Relation into an Array; if you want to do something like SELECT DISTINCT you'll want to use Product.includes(:tags).select('DISTINCT whatever').

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • My apologies, updating the answer – Michelle Tilley Aug 11 '12 at 00:53
  • Now im getting a `Mysql::Error: Unknown column 'cat_name' `. Do I need to somehow include my join table? – Yogzzz Aug 11 '12 at 01:04
  • What is your full line? You can see the SQL that would be generated by going into the console and appending `.to_sql` to the end of your scope, which may aid in debugging. – Michelle Tilley Aug 11 '12 at 01:08
  • `SELECT DISTINCT cat_name FROM `products` ` is the SQL being generated. Its selecting it from the products table, however the cat_name is a field on the tags table. I tried `Product.includes(:tags).select('DISTINCT tags.cat_name')` but that freezes my console. – Yogzzz Aug 11 '12 at 01:12