Reputation: 17803
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
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