Nicolas Maloeuvre
Nicolas Maloeuvre

Reputation: 3169

Rails-Active Record query : "where one of ... is in ... "

I have a "has many through" relationship between Post model and Hashtag model. I want all posts that match one of hashtags in a list. Currently i use this query:

hashtags_ids = [2,7,8]
Post.includes(:hashtags).where(:hashtags => {:id => hashtags_ids})

it returns the right posts, but with missing other tags. Example:
Existing post p1:
p1.content = "this is a post"
p1.hashtags = [1,2]

The query would return
p1.content = "this is a post"
p1.hashtags = [2]

Is there a way to keep other hashtags ?

Upvotes: 0

Views: 244

Answers (1)

Baldrick
Baldrick

Reputation: 24340

You could use joins instead of includes :

hashtags_ids = [2,7,8]
Post.joins(:hashtags).where(:hashtags => {:id => hashtags_ids})

With this, Rails will use several SQL requests: a first one to retrieve all the posts with at least one of the given hashtags. Next it will fire a new SQL request for each retrieved post when the hashtags collection will be accessed.

Upvotes: 2

Related Questions