0

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.

TopperH
  • 2,183
  • 18
  • 33
  • try `Post.includes(:tags).where("tags.category = ?", "foo")` – PGill Dec 05 '14 at 01:16
  • @PavittarGill pry(main)> Post.includes(:tags).where("tags.category = ?", "foo") Post Load (4.2ms) SELECT "posts".* FROM "posts" WHERE (tags.category = 'foo') SQLite3::SQLException: no such column: tags.category: SELECT "posts".* FROM "posts" WHERE (tags.category = 'foo') => # – TopperH Dec 05 '14 at 05:30

1 Answers1

1

Post.joins(:tags).where('tags.category = ?', "foo").all

The answer in the comment is where, for example, you didn't want to query by the tag but maybe wanted to include some information relating to the tag in your view. By using includes, you will avoid the N+1 problem.

Robin Fisher
  • 1,454
  • 1
  • 13
  • 23