0
votes

I have created an "has_many :through" association. I have a posts, categories and a categorization model. This categorization model has a Categorizations table which links all the post_ids to category_ids. Every post has multiple categories and every category has multiple posts. I want to list all the posts if I call an category, but to do that I have to make an array and store it in post_ids. This array gets stored in @post_ids. How can I make an array from this: "Categorization.find_by(category_id: @category_id).post_id" and store it in @post_ids?

def index
  if params[:category].blank?
  @posts = Post.all.order("created_at DESC")
else
  @category_id = Category.find_by(name: params[:category]).id
  @post_ids = Categorization.find_by(category_id: @category_id).post_id
  @posts = Post.where(id: (@post_ids)).order("created_at DESC")
end

Thanks in advance!

2

2 Answers

2
votes

After your retrieve the ActiveRecord Object

a = Categorization.where(category_id: @category_id)

Use pluck to retrieve all the post_ids by

a.pluck(:post_id) # Ensure that pluck is a ActiveRecord call and can only be used on Active Record objects.

This approach seems much cleaner.

0
votes

Simply replace

@post_ids = Categorization.find_by(category_id: @category_id).post_id

with

@post_ids = Categorization.where(category_id: @category_id).map(&:post_id)