简体   繁体   English

渴望加载多态关联

[英]Eager loading for polymorphic associations

Not sure this could fall in performance section as well as model/database section, so here goes.... 不确定这是否会属于性能部分以及模型/数据库部分,所以这里...

Let's say I have 3 models: 假设我有3个模型:

Movie {
has_one :interest, :as => :resource
}
Song {
has_one :interest, :as => :resource
}
Story {
has_one :interest, :as => :resource
}

and ... 还有...

Interest {
belongs_to :resource, :polymorphic => true
}

Now, if I need a list of all interests for all movies, and I want to show also the date those Movies objects were created (to say how old they were), then I use the lookup on resource_type attribute and then @some_interest.resource.created_at. 现在,如果我需要所有电影的所有兴趣列表,并且还想显示这些电影对象的创建日期(以说明它们的年龄),则可以使用对resource_type属性的查找,然后使用@ some_interest.resource .created_at。

The problem with this is if I have 100 movie interests, then I will get 101 queries right ? 问题是,如果我有100个电影兴趣,那么我会得到101个查询,对吗? So linear degradation. 因此线性退化。 I tried using :include => [:resource] in my query call, but it says cannot use include in polymorphic associations. 我尝试在查询调用中使用:include => [:resource],但它说不能在多态关联中使用include。

How can I either eager load or optimize this problem to avoid this severe degradation ?? 我如何急于加​​载或优化此问题以避免这种严重的退化?

Any help would be greatly appreciated !! 任何帮助将不胜感激 !!

If you are using searchlogic , there is a special syntax to deal with polymorphic relationships that may help. 如果使用searchlogic ,则有一种特殊的语法可以处理多态关系。 You can search on the has side of the relationship by specifying the name of the related class suffixed with type . 您可以通过指定后缀为type的相关类的名称,在关系的has端进行搜索。

Eg given your models, you ought to be able to do something like this to get movies created in the last 90 days: 例如,给定您的模型,您应该能够执行以下操作以获取最近90天内制作的电影:

Interest.resource_movie_type_created_at_gt(Time.now-90.days)

Searchlogic sets up the join on the related model for you, which should allay performance concerns. Searchlogic为您设置了相关模型上的联接,这可以缓解性能问题。

Of course you can always write your own SQL using the find_by_sql method. 当然,您始终可以使用find_by_sql方法编写自己的SQL。

PS. PS。 one very helpful trick is to turn on logging in the Rails console while writing searches. 一个非常有用的技巧是在编写搜索时打开Rails控制台中的日志记录 This allows you to see the SQL generated right in the console without having to dig through the logs. 这样,您就可以直接在控制台中查看生成的SQL,而不必深入研究日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM