【发布时间】: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