vendredi 12 juin 2015

Complex Rails query using ActiveRecord on Many to Many relationship

I have the following models

class Element
  has_many :tags, through: :tags_elements
end

class Tag
  has_many :elements, through: :tags_elements
end

I NEED: The elements that are related to all tags defined on a variable. i.e. all elements with tags: ["gt40", "car"]

I have tried the following:

class Element   
  scope :search_tags, lambda { |df|
    joins(tags_elements: :tag)
    .where('tags.name IN (?) ', df)
    .distinct('id')
  }

So I can do

tag_list = ["gt40","car"]
Element.search_tags(tag_list)

But it returns evert element that has ANY of the tags. However I need the elements that are related to ALL tags.

Any help?

Aucun commentaire:

Enregistrer un commentaire