0

假设我在 Rails 中有以下模型:

class User < ActiveRecord::Base
  has_many :aliases
  has_many :comments, :as => :commentable
end

class Alias < ActiveRecord::Base
  belongs_to :user
  has_many   :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

我将如何获取一个用户及其所有别名下的所有评论?

谢谢你。

4

1 回答 1

1

我对这种模式很满意。这是三个查询,不包括获取用户的查询。您可以通过 ORing 可评论用户和可评论别名的标准将其减少到两个,我为此使用了 squeel gem

实际上,对于您正在做的事情,您可能会考虑始终映射到别名而不是用户,然后始终确保用户具有单例别名。它将消除特殊情况处理并使事情变得更容易。

user = User.first # For example
aliases = user.aliases # Add .to_a if desired
comments = user.comments.to_a + Comment.where(commentable_type: Alias.name).
  where(commentable_id: aliases.map(&:id)).to_a
于 2013-06-29T15:47:45.640 回答