简体   繁体   English

Ruby on Rails“ has_many:through”关联返回一个数组

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

I have created an "has_many :through" association. 我创建了一个“ has_many:through”关联。 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. 此分类模型具有一个分类表,该表将所有post_id链接到category_id。 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. 如果要调用类别,我想列出所有帖子,但是要做到这一点,我必须制作一个数组并将其存储在post_ids中。 This array gets stored in @post_ids. 该数组存储在@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? 我如何从中创建一个数组:“ Categorization.find_by(category_id:@category_id).post_id”并将其存储在@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 检索ActiveRecord对象后

a = Categorization.where(category_id: @category_id)

Use pluck to retrieve all the post_ids by 使用pluck通过以下方式检索所有post_id

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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