Rails 用于匹配多个 habtm 记录的 arel 查询

Rails arel query for matching multiple habtm records

我有如下设置,

Post
- has_and_belongs_to_many :tags

Tag
- has_and_belongs_to_many :posts

问题:

I want to find all the posts which have social, informative tags in it, I can also use their ID's suppose 1 and 2. Using arel or ActiveRecord or plain SQL.

我可以找到 postsany 个标签,使用: post_tags[:tag_id].in([1, 2])

我可以找到 postsnone 个标签,使用: post_tags[:tag_id].not_in([1, 2])

但我做不到: post_tags[:tag_id].in_all([1, 2]) 那是因为一条记录无法匹配所有标签 ID。

我该怎么做?

找到答案了!

posts = Arel::Table.new(:posts)
posts_tags = Arel::Table.new(:posts_tags)

tag_ids = [1, 2]

ids_predicate = 
  posts.
    project(posts[:id]).
    join(posts_tags).on(
      posts[:id].eq(posts_tags[:post_id])
    ).
    where(
      posts_tags[:tag_id].in(tag_ids)
    ).
    group(posts[:id]).
    having(
      posts_tags[:tag_id].count.eq(tag_ids.count)
    )


Post.where(posts[:id].in(ids_predicate))

我觉得很酷!