Roberto Pezzali
Roberto Pezzali

Reputation: 2494

Activerecord complex join

I have a problem with an activerecord join.

I have an object "user" that follows some items, and an object "content" that has some followable items (brands in this case) associated.

u and c are my user and my content.

Now I have these two queries:

bf = u.follows.where('followable_type = ?', "Brand").map(&:followable_id)

[22, 188, 182, 71, 24, 2]

c.brands.map(&:id)

[2]

I need to obtain an array with the values present in both query, so in this case [2].

How can I write a single query?

Something like

bf = u.follows.where('followable_type = ?', "Brand").where followable_id are inside c.brands_ids

Update:

brands = author.follows.where('followable_type = ?', "Brand").where(followable_id: content.brands.map(&:id)).map(&:followable).map(&:name).join(', ')

Upvotes: 1

Views: 67

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

Try using this query:

sql_subquery = u.follows.where(followable_type: 'Brand').select(:followable_id).to_sql
u.follows.where( followable_id: sql_subquery )

Also, a good advice, try using complete names for variables. It makes your code more readable, even for you.

Upvotes: 1

Related Questions