如何优化此活动记录查询?

时间:2015-09-02 13:29:27

标签: ruby-on-rails ruby activerecord

有这些模型:

患者

Patient has_many MedicalOrders

MedicalOrder

MedicalOrder belongs_to Patient
MedicalOrder has_many Tasks

任务

Task belongs_to MedicalOrder
Task has_many ControlMedicines

ControlMedicine

ControlMedicine belongs_to Task

这段代码可以让实际的@病人 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和包含的内容,但所有示例仅限于从两个相关模型中获取数据。

1 个答案:

答案 0 :(得分:3)

您可以使用Rails中的seekBar1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { currentValue = progress; } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } }); 来允许ActiveRecord为您创建联接。

has_many through

编写您的查询,如:

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

生成SQL,如:

@patient.control_medicines