多态关联的预加载
不确定这可能属于性能部分以及模型/数据库部分,所以这里......
假设我有 3 个模型:
Movie {
has_one :interest, :as => :resource
}
Song {
has_one :interest, :as => :resource
}
Story {
has_one :interest, :as => :resource
}
并且......
Interest {
belongs_to :resource, :polymorphic => true
}
现在,如果我需要所有电影的所有兴趣列表,并且我还想显示这些 Movies 对象的创建日期(说明它们的年龄),然后我使用对 resources_type 属性的查找,然后使用 @some_interest.resource.created_at 的查找。
问题是如果我有 100 个电影兴趣,那么我会得到 101 个查询,对吧?所以线性退化。我尝试使用 :include => [:resource] 在我的查询调用中,但它说不能在多态关联中使用包含。
我怎样才能立即加载或优化这个问题以避免这种严重的退化?
任何帮助将不胜感激!
Not sure this could fall in performance section as well as model/database section, so here goes....
Let's say I have 3 models:
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.
The problem with this is if I have 100 movie interests, then I will get 101 queries right ? So linear degradation. I tried using :include => [:resource] in my query call, but it says cannot use include in polymorphic associations.
How can I either eager load or optimize this problem to avoid this severe degradation ??
Any help would be greatly appreciated !!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 searchlogic,有一种特殊的语法来处理多态关系可能会有所帮助。您可以通过指定以
type
为后缀的相关类的名称来搜索关系的has
端。例如,给定您的模型,您应该能够执行类似的操作来获取过去 90 天内创建的电影:
Interest.resource_movie_type_created_at_gt(Time.now-90.days)
Searchlogic 将连接设置为适合您的相关模型,这应该可以减轻性能问题。
当然,您始终可以使用
find_by_sql
方法编写自己的 SQL。附言。一个非常有用的技巧是 在 Rails 控制台中打开日志记录写作搜索。这使您可以直接在控制台中查看生成的 SQL,而无需深入查看日志。
If you are using searchlogic, there is a special syntax to deal with polymorphic relationships that may help. You can search on the
has
side of the relationship by specifying the name of the related class suffixed withtype
.E.g. given your models, you ought to be able to do something like this to get movies created in the last 90 days:
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.
Of course you can always write your own SQL using the
find_by_sql
method.PS. one very helpful trick is to turn on logging in the Rails console while writing searches. This allows you to see the SQL generated right in the console without having to dig through the logs.