Rails 有没办法对 polymorphic association 的数据进行 Eager Loading?

zhangner · 2013年04月02日 · 最后由 zhangner 回复于 2013年04月03日 · 2647 次阅读

有个 Model A 通过 Polymorphic Association 的方式与多个 Model B、C、D 进行关联,其中 Model B 中又 belongs_to 另外的 Model,如 E。那么通过对 Model A 的查询上添加 includes 可以对 Model B、C、D 进行 Eager Loading,但透过 Model B 访问其 belongs_to 的模型 E 时,怎样做 Eager Loading 呢?

有时候用代码会更好描述你的意思,还有不要用 A B C 这些代词,用实际的例子别人更容易看懂

abc 容易晕

#1 楼 @huacnlee 简单点就是有下面几个 Model 和关系

class Action < ActiveRecord::Base
    belongs_to :actionable, :polymorphic => true
end
class Book < ActiveRecord::Base
    has_one :action, :as => :actionable
    has_many :items
end
class Group < ActiveRecord::Base
   has_one :action, :as => :actionable
   has_many :topics
end

然后通过下面的查询从 Action 中取记录,

Action.includes(:actionable).where("created_at < ?", Time.now).limit(50)

通过 Polymorphic 取到各个关联的 Model,比如有条记录是一个 book 实例,要从这个 book 实例中取 items 的时候产生了 N+1 查询。

#2 楼 @lidashuang 同时如果取到的记录是 group 实例,从中取 topics 的时候也会有 N+1 查询,这时要对这查询怎么做 Eagar Loading 呢?

到视图再做片断缓存。

#5 楼 @Rei 那意思是说这个 Eagar Loading 是躲不掉的咯?

Eagar Loading 本来就是通过 sql 的 join 搞出来,可能。 polymophic 搞不了 join 吧~ join 不同的表?

#7 楼 @calebx Eagar Loading 真不是 join 搞出来的,应该是前面的查询拿 id 列表,再做次 in 查询。

#6 楼 @zhangner 简单地说:做不了

#9 楼 @Rei 好的,thanks。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号