问题描述
有谁知道一个方法来确定是否一个Rails协会一直渴望装?
Does anyone know a way to determine if a Rails association has been eager loaded?
我的情况:我有一个结果集,其中有时协会之一是渴望加载,有时事实并非如此。如果不是急于装,然后我想用的ActiveRecord的find来查找关联。如果是急于装,我想用检测。
My situation: I have a result set where sometimes one of the associations is eager loaded, and sometimes it isn't. If it isn't eager-loaded, then I want to look up associations using ActiveRecord's find. If it is eager loaded, I want to use detect.
举例来说,假设我在我的项目模型的has_manyshipping_info对象的数组。然后:
For example, say that I have a "has_many" array of shipping_info objects in my item model. Then:
如果项目急于装,最有效载荷为:
If item is eager loaded, most efficient load is:
item.shipping_infos.detect { |si| si.region == "United States" }
如果产品没有急于装,最有效载荷为:
If item isn't eager loaded, most efficient load is:
item.shipping_infos.where(region: "United States").first
但是,除非我知道是急于装,我不知道哪个code调用有效地得到记录。如果我用第一种方法时,它并不急于装,那我也看多了起来DB的记录比必要。如果我用的时候就急于加载的第二种方法,那么我渴望加载的对象都被忽略。
But unless I know whether it is eager loaded, I don't know which code to call to get the record efficiently. If I use the first method when it wasn't eager loaded, then I have to look up more DB records than necessary. And if I use the second method when it was eager loaded, then my eager loaded objects are ignored.
推荐答案
item.shipping_infos.loaded?会告诉你。
item.shipping_infos.loaded? will tell you.
(我得说,但是:这条道路通向疯狂......编写的测试加载code #detect和#find之间做出选择之前,要确保这种情况下的真正的问题?相对于其他一切事情。如果这不是最慢的东西你的应用程序做,增加额外的code路径增加了不必要的复杂性。仅仅因为你可能会浪费一点力气数据库并不意味着你需要修复它 - 它可能并不重要,在任何衡量的方式)
(I gotta say, though: this path leads to madness... before writing code that tests loaded? to decide between #detect and #find, make sure this instance really matters, relative to everything else that's going on. If this isn't the slowest thing your app does, adding extra code paths adds unnecessary complexity. Just because you might waste a little database effort doesn't mean you need to fix it - it probably doesn't matter in any measurable way.)
这篇关于如何确定是否Rails的协会是急于装的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!