小编And*_*ith的帖子

rails polymorphic with includes基于类的类型

假设我们有这些模型

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另一个关联包含其他内容,以及如果该关联需要更多包括什么?

activerecord ruby-on-rails polymorphic-associations eager-loading ruby-on-rails-3

10
推荐指数
1
解决办法
871
查看次数