考虑以下多态关系:
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
答案 0 :(得分:0)
Comment.where(commentable: @user.posts).or(Comment.where(commentable: @user.groups))