简体   繁体   中英

Ruby on Rails “has_many :through” association return an array

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!

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM