有这些模型:
病人
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/