ActiveRecord has_and_belongs_to_many 关系的 CONTAIN 或 LIKE sql 语句

CONTAIN or LIKE sql statement for ActiveRecord has_and_belongs_to_many relationship

我有 2 个 ActiveRecords:文章和标签,处于多对多关系中。基本上我想知道如何 select 使用 CONTAINS 或 LIKE 条件,即。定义多对多关系的条件以在数组中包含指定的子集。

我正在尝试的代码结构如下:

 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)

如果您有不同的表,那么您必须在加入时使用 joins 然后 specify a condition

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

如果您希望查询更加灵活,您还可以使用 Arel 并编写如下内容:

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

您可以在 this answer 中阅读有关 matches 的更多信息。

与纯字符串甚至哈希条件相比,我更喜欢 Arel 条件。