渴望加载(包括)多态关联

时间:2017-07-21 02:02:38

标签: ruby-on-rails ruby activerecord eager-loading

考虑以下多态关系:

class Comment
  belongs_to :commentable, polymorphic: true
end

class User
  has_many :posts
  has_many :groups
end

class Group
  belongs_to :user
  has_many :comments, as: :commentable
end

class Post
  belongs_to :user
  has_many :comments, as: :commentable
end

用户基本上有post条评论和group条评论。我想返回用户的总评论。实现这一目标的一种方法是:

posts = @user.posts.map {|c| c.comments}.flatten
groups = @user.groups.map {|c| c.comments}.flatten

但是,这是数据库密集型的。可以像这样急切地加载:

Comment.includes(:commentable).where(commentable: {user_id: self.id})
# ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :commentable

1 个答案:

答案 0 :(得分:0)

Comment.where(commentable: @user.posts).or(Comment.where(commentable: @user.groups))