ActiveRecord会在类别数组及其所有类别中获取所有Post

时间:2018-09-02 12:25:36

标签: ruby-on-rails rails-activerecord

我有两个这样的模型:

class Category < ApplicationRecord
  has_and_belongs_to_many :posts
end

class Post < ApplicationRecord
  has_and_belongs_to_many :categories
wns

我正在尝试获取所有类别数组中的所有帖子:

Post.includes(:categories).where(categories: { name: current_user['categories'] })

问题是当帖子有多个类别时,不包括这些类别。每个帖子仅返回current_user['categories']内部明确提及的类别。

基本上,如果我正在搜索类别A和类别B current_user['categories'] = ['A','B']中的所有帖子,如果帖子属于类别A和类别C,则我的查询将仅返回类别A。我希望帖子返回类别A和C

1 个答案:

答案 0 :(得分:2)

这个怎么样?或者帖子和类别之间还有另一个表格

post_ids = Category.where(name: current_user['categories']).collect(&:post_id).uniq

您也可以使用更好的拔毛

post_ids =  Category.where(name: current_user['categories']).pluck("distinct post_id")

Post.includes(:categories).where(id: post_ids)
相关问题