Ruby on rails 使用rails按类别过滤

Ruby on rails 使用rails按类别过滤,ruby-on-rails,ruby,postgresql,activerecord,rails-activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,Rails Activerecord,我有两个模型Recipe和Category,它们与has_关联,并且_属于_许多,现在我需要按类别筛选配方,当用户检查类别时,我接收已检查类别ID的数组,并创建一个筛选配方的范围,如下所示: scope :filter, -> (category_ids){ includes(:categories).where(categories: {id: category_ids}) if category_ids.present? } 并在recipes controller中使用此范围 Re

我有两个模型Recipe和Category,它们与has_关联,并且_属于_许多,现在我需要按类别筛选配方,当用户检查类别时,我接收已检查类别ID的数组,并创建一个筛选配方的范围,如下所示:

scope :filter, -> (category_ids){ includes(:categories).where(categories: {id: category_ids}) if category_ids.present? }
并在recipes controller中使用此范围

Recipe.filter(params_index[:category_ids])
私人的

def params_index
  params.permit(category_ids: [])
end

问题是,如果任何类别id与用户传递的类别id匹配,它将返回recipe,例如,如果用户检查了早餐和沙拉,我的过滤器将返回所有早餐和所有沙拉,但我只需要包含早餐和沙拉两个类别的食谱。我可以用activerecord做这件事吗?对db来说,查询应该是什么样子?我正在使用rails 5和postgresql。(希望得到您的帮助)

您可以通过
小组
拥有

scope :filter, -> (category_ids) { 
  return unless category_ids.present?
  includes(:categories).where(categories: { id: category_ids })
                       .group(:id).having("count(*) = ? ", category_ids.size)
}

group(:recipe\u id)。拥有(“count(*)=?”,category\u id.size)
?我将:recipe\u id替换为:id,效果很好。谢谢!非常感谢!)