Ruby-on-rails – Rails: Check if associations exist in has_many

conditional-statementshas-manyruby-on-rails

Is it possible to check if multiple associations exist in has_many? In this case I want to check if there is a book which has three tags "a", "b" and "c".

(Book and Tag are associated via many to many.)

if Book.all.tags.find("a", "b", "c").any?
  # Yay!
  # There is at least one book with all three tags (a, b & c)
end

Best Answer

I think this will do the trick (works on has_many):

Book.includes(:tags).where(tags: { name: ['a', 'b', 'c'] }).any?

Breaking it down:

The includes tells Rails to use eager loading to load tags, versus loading them one at a time. This also causes it to pay attention to tags in the queries and generate smarter queries.

The where condition is pretty simple, and passing the array just converts an = comparison into an IN ('a', 'b', 'c') condition.

Rails is smart about any?, so rather than loading the records (which generates a garish query, btw) it generates one that just loads the count.