【问题标题】:Rails: Query for has many through associationsRails:查询有很多通过关联
【发布时间】:2018-01-28 21:43:53
【问题描述】:

我有以下关联

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用 includes 加载每个帖子的类别

    current_user.posts.includes(:categories)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多