I have a rails 4 that has a Post model related to a Tag model by an habtm relation. Tags have a name field and a category field. Multiple tags can have the same category.
I need a view that displays only posts that have at least one tag belonging to the "foo" category. Foo is static and will always remain "foo".
I've been able to make it work using this code in my posts controller:
def myview
ids = []
Tag.where(category: 'foo').each do |tag|
tag.posts.each do |post|
ids << post.id
end
end
@posts = Post.where(id: ids).all
end
Despite working my code looks really ugly to read.
I'm sure rails provides a way like "@posts = Post.where tag categories include 'foo'.all" but I cannot figure out a way. I'm sure I'm missing something very obvoius.