我有以下关联
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
那么我怎样才能获得相关的帖子类别。
答案 0 :(得分:1)
您可以使用包含来加载每个帖子的类别
current_user.posts.includes(:categories)