Rails: How would I retrieve records where child element includes any of another array?

121 Views Asked by At

I have a User and Document model, which both have tag_lists (from acts_as_taggable)

I want to find the Documents that have any of the tags a certain user has. So for example,

user.tag_list = ["ceo" , "sales"]
documentA.tag_list = ["ceo"] 
documentB.tag_list = ["all-users'] 
documentC.tag_list = ["sales", "marketing"] 
documentD.tag_list = ["marketing"]

I want to do something like

Document.where(tag_list.includes_any?("all-users" || user.tag_list))
-> which would retrieve document A,B,C.

Obviously the syntax is wrong, but you get the idea. How would I do this in an efficient way?

-------update

Just fyi, the tag_list is not a direct attribute of either User or Document model, but a active record relation from the acts_as_taggable gem: how would I call this in a .where operator?

2.1.1 :036 > Document.last.tag_list
  Document Load (3.7ms)  SELECT  "assignable_objects".* FROM "assignable_objects"  WHERE "assignable_objects"."type" IN ('Document')  ORDER BY "assignable_objects"."id" DESC LIMIT 1
  ActsAsTaggableOn::Tag Load (3.5ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)  [["taggable_id", 52], ["taggable_type", "AssignableObject"]]
 => []
1

There are 1 best solutions below

3
On

This might help you:

    Document.where((tag_list-["all-users", user.tag_list].flatten).size != tag_list.size)