Rails 添加自定义预加载
我在 Rails 中有许多自定义 find_by_sql 查询。我想对它们使用急切加载,但似乎没有一个好的方法来做到这一点。
我看到 eager_custom.rb 文件四处浮动,现在它似乎无法与 Rails 一起使用。看起来 Rails 现在的预加载方式有所不同,它使用 2 个查询(常规查询加上第一个查询中的 id IN 的查询),而不是过去使用的单个连接查询。
我的问题是,如果我执行自定义 SQL 查询,然后执行“id IN”查询,是否有办法将关联对象添加回初始查询结果中?
例如,我有使用 find_by_sql 加载的主题,然后我找到主题 id 位于主题 id 中的主题图像,有没有办法将图像手动添加回主题?
谢谢
I have a number of custom find_by_sql queries in Rails. I would like to use eager loading with them but there doesn't seem to be a good way to do this.
I have seen the eager_custom.rb file floating around and it doesn't seem to work with Rails now. It appear Rails does eager loading differently now, using 2 queries (the regular query plus a query where the 'id IN' the ids from the first query), instead of the single join query used in the past.
My question is if I do a custom SQL query, then do 'id IN' query, is there a way to add back associated objects into the initial query results?
For example I have topics loaded with find_by_sql, then I find topic images where the topic id is in the topics ids, is there a way to add the images manually back to the topics?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所注意到的,Rails 2.1 中引入了一种新的急切/预加载,它使用
id IN (...)
进行多个查询。此方法通常速度更快,尤其是在预加载多个关联时。您可以通过使用从 ActiveRecord 继承的preload_associations
类方法(不推荐),通过find_by_sql
手动使用此功能。例如:preload_associations
方法是受保护的,因此您必须从类内部调用它,并且它需要 (1) 对象数组,(2) 数组、哈希或关联符号 (与find
的:include
选项格式相同),以及 (3) 选项哈希。有关更多详细信息,请参阅 ActiveRecord::AssociationPreload::ClassMethods 模块的文档。然而,话虽如此,这种技术肯定是不可取的,因为 Rails 文档不鼓励程序员直接使用
preload_associations
。您确定必须使用find_by_sql
吗?您确定您知道find
所采用的所有选项吗? (:select
、:from
、:joins
、:group
、:having
等)我并不是说您不需要find_by_sql
,但可能值得花几分钟来确定。As you noticed, in Rails 2.1 a new kind of eager/pre-loading was introduced which uses multiple queries with
id IN (...)
. This method is usually faster, especially when there are multiple associations being pre-loaded. You can use this functionality manually withfind_by_sql
by using thepreload_associations
class method inherited from ActiveRecord (not recommended). For example:The
preload_associations
method is protected, so you must call it from within the class, and it takes (1) an array of objects, (2) an array, hash, or symbol of associations (same format asfind
's:include
option), and (3) an options hash. See the documentation for the ActiveRecord::AssociationPreload::ClassMethods module for more details.However, having said all of that, this technique is certainly undesirable as the Rails documentation discourages programmers from using
preload_associations
directly. Are you sure you have to usefind_by_sql
? Are you sure you know all of the optionsfind
takes? (:select
,:from
,:joins
,:group
,:having
, etc) I'm not saying you don't needfind_by_sql
, but it might be worth a few minutes to make sure.