Gal Ben-Haim
Gal Ben-Haim

Reputation: 17803

how to get all items of has_many through association

I have a post model that has many tags through taggings. let's say:

@posts = Post.followed_by(@user)

I want to get all tags of @posts.

I can do it with something like:

@posts.each do |post|
  @tags << post.tags
end

how can I do it in a more efficient way?

Upvotes: 0

Views: 1251

Answers (1)

jdoe
jdoe

Reputation: 15771

Try this:

Tag.joins(:taggings).where(taggings: {post_id: @posts.map(&:id)})

If @posts is a relation (not an array), you can simplify your query:

Tag.joins(:taggings).where(taggings: {post_id: @posts})

Upvotes: 2

Related Questions