blop
blop

Reputation: 31

ActiveRecord get all Post inside array of categories with all their categories

I have two models like this:

class Category < ApplicationRecord
  has_and_belongs_to_many :posts
end

class Post < ApplicationRecord
  has_and_belongs_to_many :categories
wns

I'm trying to get all posts that are inside an array of categories:

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

The problem with this is when a Post has several categories, those aren't included. Only categories that are explicitly mentioned inside current_user['categories'] are returned for each post.

Basically if I'm searching for all posts inside category A and B current_user['categories'] = ['A','B'], if a post belongs to categories A and C, my query will return only category A. I want post to return category A AND C.

Upvotes: 1

Views: 208

Answers (1)

praga2050
praga2050

Reputation: 773

how about this one ? or there is another table between posts & categories

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

also you can use much better pluck too

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

Post.includes(:categories).where(id: post_ids)

Upvotes: 2

Related Questions