Ruby on rails 在Rails中有许多虽然带有not子句
我有一个Ruby on rails 在Rails中有许多虽然带有not子句,ruby-on-rails,activerecord,has-many-through,Ruby On Rails,Activerecord,Has Many Through,我有一个Post对象,它通过Post\u category拥有许多类别 我如何才能找到所有未包含在特定类别中的帖子?--范围限于某个用户,因此 @category = Category.find(params[:id]) @posts = current_user.posts.where # post is not included @category 我试过这个,但不起作用: user.posts.joins(:post_categories).where.not(post_categori
Post
对象,它通过Post\u category
拥有许多类别
我如何才能找到所有未包含在特定类别中的帖子?--范围限于某个用户,因此
@category = Category.find(params[:id])
@posts = current_user.posts.where # post is not included @category
我试过这个,但不起作用:
user.posts.joins(:post_categories).where.not(post_categories: { category_id: @category })
注意,我不是在寻找没有类别的帖子。我正在寻找没有特定类别的帖子,其中可能包括没有类别的帖子
我认为问题在于加入。。。根据定义,连接意味着我不会包括任何没有类别的文章,对吗?连接在Rails中可能会有所不同,但默认(我相信)是使用内部连接,这确实需要在两个表中都存在-如果您要查找没有任何类别的文章,则需要不同的策略
我能想到的最“讽刺”的方法是分两步:获取你不想要的帖子的ID,然后获取你想要的帖子:
excepted_ids = PostCategory.where(category_id: @category.id).select(:post_id).distinct
@posts = Post.where.not(id: excepted_ids)
我还没有测试过这个,所以它可能不像我预期的那样工作 请点击此处:。