简体   繁体   English

ActiveRecord自定义has_many关联对数据库进行多次调用

[英]ActiveRecord custom has_many association makes multiple calls to the database

I have a pair of ActiveRecord objects that have a belongs_to ... has_many association, with the has_many association being custom-made. 我有一对ActiveRecord对象,它们具有belongs_to ... has_many关联,has_many关联是自定义的。 Example: 例:

First AR object: 第一个AR对象:

class Car < Vehicle
    has_many :wheels, class_name: "RoundObject", foreign_key: :vehicle_id, conditions: "working = 1"

    validates_presence_of :wheels
    ...
end

Second AR object: 第二个AR对象:

class RoundObject < ActiveRecord::Base
    belongs_to :vehicle
    ...
end

Please note that the above is not indicative of my app's function, simply to outline the association between my two AR objects. 请注意,上述内容并不表示我的应用程序的功能,只是为了概述我的两个AR对象之间的关联。

The issue I'm having is that, when I reset the cache (and thus my Rails app re-caches all AR objects in the database), when it comes time for the RoundObject object to get re-cached, it makes multiple calls to the database, one for each unique vehicle_id associated with the collection of RoundObject s. 我遇到的问题是,当我重置缓存(因此我的Rails应用程序重新缓存数据库中的所有AR对象)时,当RoundObject对象重新缓存时,它会多次调用数据库,一个用于与RoundObject集合相关联的每个唯一vehicle_id The SQL commands being run are output to the console, so this is what my output looked like: 正在运行的SQL命令输出到控制台,所以这就是我的输出:

  RoundObject Load (2.0ms)  SELECT `round_objects`.* FROM `round_objects` WHERE `round_objects`.`vehicle_id` = 28 AND (active = 1)
  RoundObject Load (1.0ms)  SELECT `round_objects`.* FROM `round_objects` WHERE `round_objects`.`vehicle_id` = 29 AND (active = 1)
  RoundObject Load (2.0ms)  SELECT `round_objects`.* FROM `round_objects` WHERE `round_objects`.`vehicle_id` = 30 AND (active = 1)

My app has several other AR objects that use the built-in has_many association without any modifications, and I notice that they only hit the database once when resetting the cache. 我的应用程序有几个其他AR对象使用内置的has_many关联而没有任何修改,我注意到它们只在重置缓存时才访问数据库一次。 For instance: 例如:

Micropost Load (15.0ms)  SELECT `microposts`.* FROM `microposts` INNER JOIN `posts` ON `posts`.`id` = `microposts`.`post_id` WHERE `microposts`.`active` = 1 AND `posts`.`active` = 1

My question is, how can I make my AR object only hit the database once on cache reset, while still maintaining the custom has_many association I need? 我的问题是,如何在缓存重置时让我的AR对象只访问数据库一次,同时仍然保持我需要的自定义has_many关联? Can I manually force a join on the SQL query being called, and will this help? 我可以在被调用的SQL查询上手动强制连接,这会有帮助吗?

Thank you! 谢谢!

You can use includes method while calling your Vehicle object to include the RoundObject. 您可以在调用Vehicle对象时使用includes方法来包含RoundObject。
It will go like this: 会是这样的:

Vehicle.where(conditions_for_getting_data).includes(:round_object)

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

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