简体   繁体   English

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

[英]Eager load (includes) polymorphic association

Consider the following polymorphic relationship: 考虑以下多态关系:

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

Essentially a user has post comments and group comments. 本质上,用户具有post评论和group评论。 I want to return user total comments. 我想返回用户的总评论。 One way of achieving this is: 实现此目的的一种方法是:

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

However, this is database intensive. 但是,这是数据库密集型的。 It is possible to eager load here like this: 可能希望像这样在这里加载:

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

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

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