rails polymorphic with includes基于类的类型

And*_*i S 10 activerecord ruby-on-rails polymorphic-associations eager-loading ruby-on-rails-3

假设我们有这些模型

class Message
  belongs_to :messageable, polymorphic: true
end

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
end

class Rating
  belongs_to :user
end

class Comment
  belongs_to :ticket
end
Run Code Online (Sandbox Code Playgroud)

现在我想加载所有消息(具有关联的tickets或者users),并根据类的类型加载eager,commentsfor for ticketsratingsforusers

当然Message.includes(:messageable).order("created_at desc")只会包含直接关联的对象,但问题是如何包含从每个模型类型派生的不同关联类型(即在此示例中,如何预先加载comments for ticketsratings for users)?

这只是一个简单的例子,但是更复杂的情况呢,我想为user另一个关联包含其他内容,以及如果该关联需要更多包括什么?

Zac*_*emp 2

我能想到的唯一方法是使用通用名称复制每个模型上的关联:

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  has_many :messageable_includes, class_name: "Comment"
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
  has_many :messageable_includes, class_name: "Rating"
end

Message.includes(:messageable => :messageable_includes) ...
Run Code Online (Sandbox Code Playgroud)

我不确定我是否会使用此策略作为广泛的解决方案,但如果您的情况变得复杂,那么它可能对您有用。