0

I have 2 ActiveRecords: Article and Tag, in a many to many relationship. Basically I want to know how to select with a CONTAINS or LIKE condition, ie. to define a condition on a many to many relationship to contain a specified subset within an array.

The code structure I am trying to work out is as follows:

 tag_names = ["super", "awesome", "dope"]
 tags = Tag.where("name IN (?)", tag_names)

 # The following is my non-working code to illustrate
 # what I'm trying to do:
 articles = Article.where("tags CONTAINS (?)", tags)
 articles = Article.joins(:tags).where("articles.tags CONTAINS (?)", tags)
JackyJohnson
  • 3,106
  • 3
  • 28
  • 35

1 Answers1

0

If you have different tables then you have to use joins and then specify a condition on your join:

Article.joins(:tags).where('tags.id IN ?', tag_ids)

If you want more flexibility on you queries, you could also use Arel and write something like the following:

tags = Tag.arel_table
tags_ids = Tag.where(tags[:name].matches("%#{some_tag}%"))
Article.joins(:tags).where(tagss[:id].in(tags_ids))

You can read more about matches in this answer.

I prefer Arel conditions over pure String or even Hash conditions.

Community
  • 1
  • 1
Yan Foto
  • 10,850
  • 6
  • 57
  • 88