【问题标题】:Filter by all ids in an array按数组中的所有 id 过滤
【发布时间】:2019-06-02 00:28:00
【问题描述】:

我有两个模型,都具有has_and_belongs_to_many 关系。

class Movie < ApplicationRecord
  has_and_belongs_to_many :genres
end
class Genre < ApplicationRecord
  has_and_belongs_to_many :movies
end

例如,在电影索引页面上,我希望能够按流派进行过滤。对于过滤器表单,我有一个类型的多选框,在提交时会发送一个 id 数组。

如何找到与数组中所有这些 id 匹配的电影,而不是使用 Active Record 的任何 id?例如,如果用户选择恐怖片和喜剧片,它应该过滤出既是恐怖片又是喜剧片的电影,而不仅仅是恐怖片或喜剧片。

ids = params[:genres]
Movie.includes(:genres).where(genres: {id: ids})

上面的示例查找任何恐怖或喜剧电影。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    通过使用joinsgrouphaving 来解决这个问题。

    ids = params[:genres]
    
    Movie.joins(:genres)
      .where(genres: {id: ids})
      .group(:id)
      .having("count(*) = #{ids.count}")
    

    这基本上会过滤掉重复的匹配项,并仅返回与原始数组计数具有相同结果数量的电影。这意味着如果数组计数为 3,则只有原始 joins 查询中具有 3 个结果的电影才会匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多