Rails:查询有很多通过关联

时间:2017-08-20 20:33:28

标签: ruby-on-rails activerecord rails-activerecord has-many-through

我有以下关联

class Post < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, through: :categorizations

class Categorization < ActiveRecord::Base
  belongs_to :category
  belongs_to :post
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :posts, through: :categorizations
end

对于用户,我会收到所有帖子,

@posts = current_user.posts

我需要与@posts相关的所有类别。所以我需要这样的东西

@categories = @posts.categories

那么我怎样才能获得相关的帖子类别。

1 个答案:

答案 0 :(得分:1)

您可以使用包含来加载每个帖子的类别

current_user.posts.includes(:categories)
相关问题