ac360
ac360

Reputation: 7835

Rails - How Do I do this Query? Get One of Each Record

I have a BlogPost model with a :category attribute. I am making a new BlogPost form, and I would like for the select menu to populate itself with each category entered in previous records by the user.

Therefore, I need one query to find all BlogPosts with a User ID, and then round up a list of each category they have entered. The same category will exist in multiple records, but of course I only want to return copy of it for the select menu.

Thank you :)

Upvotes: 1

Views: 171

Answers (1)

m_x
m_x

Reputation: 12564

You can SELECT DISTINCT categories returned an INNER JOIN to the right user :

Category
  .joins( :posts )
  .where( posts: { user_id: current_user.id } )
  .uniq

This should send a query like this :

SELECT DISTINCT categories.*
FROM categories
  INNER JOIN posts ON posts.category_id = categories.id
WHERE posts.user_id = [whatever]

EDIT NOTE: be wary that uniq is both a method on a Relation and on an Array. Be sure to call it on the relation before it is cast to an array, or you will perform the uniq on an array of non-distinct results, which works too, but is absurd performance-wise.

Upvotes: 3

Related Questions