ruby-on-rails - 如何优化此事件记录查询?

标签 ruby-on-rails ruby activerecord

有这些模型:

病人

Patient has_many MedicalOrders

医嘱

MedicalOrder belongs_to Patient
MedicalOrder has_many Tasks

任务

Task belongs_to MedicalOrder
Task has_many ControlMedicines

控制医学

ControlMedicine belongs_to Task

还有这段代码可以获取实际的@patient 的control_medicines:

def index
 @control_medicines = []

 @patient.medical_orders.each do |mo|
    mo.tasks.order(created_at: :desc).each do |t|
        t.control_medicines.each do |cm|
            @control_medicines << cm
        end
    end
  end
end

我知道这不是查询关联模型的最佳方式,但还没有弄清楚如何使用 .includes() 方法来实现。主要是因为 .includes() 只能被调用到一个类(例如,Patient.includes())并且它们不适合嵌套模型,就像在这种情况下.

我读过有关预加载、eager_loading 和包含的内容,但所有示例都仅限于从两个关联模型获取数据。

最佳答案

您可以在 Rails 中使用 has_many through 来允许 ActiveRecord 为您进行连接。

class Patient < ActiveRecord::Base
  has_many :medical_orders
  has_many :tasks, through: :medical_orders
  has_many :control_medicines, through: :tasks
end

像这样编写您的查询:

@patient.control_medicines

生成的 SQL 如下:

SELECT "control_medicines".* FROM "control_medicines" 
INNER JOIN "tasks" ON "tasks"."id" = "control_medicines"."task_id" 
INNER JOIN "medical_orders" ON "medical_orders"."id" = "tasks"."medical_order_id" 
WHERE "medical_orders.patient_id"  = $1  [["id", 12345]]

关于ruby-on-rails - 如何优化此事件记录查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354577/

相关文章:

ruby-on-rails - Rails 3 ActiveRecord 预先加载范围

mysql - 如何快速查看数据库中是否存在大量记录?

ruby-on-rails - 将 Twitter Bootstrap Carousel 添加到 Rails 应用程序

ruby - 有没有一种方法可以只删除 1 个匹配的数组元素?

ruby-on-rails - 核心中的 find_by() 和 FinderMethods 中的 find_by() 有什么区别?

ruby-on-rails - Cron 作业无法运行,crontab 使用什么语法?

ruby - ActionMailer 未实例化正确的邮件程序类

ruby-on-rails - 如何在 Rails 中查找 ID 从一个数字到另一个数字的所有对象?

ruby-on-rails - 未调用自定义回形针处理器

ruby-on-rails - 失败的 rspec 测试应该通过