在 Rails 中,如何創建過濾相關 has_one 屬性的作用域?我有兩個模型,Patient和Appointment. 在s上Patient宣告has_many關系Appointment。現在我要添加一個next_appointment關系:
class Appointment < ActiveRecord::Base
end
class Patient < ActiveRecord::Base
has_many :appointments, class_name: "::Appointment", foreign_key: :patient_id, inverse_of: :patient
has_one(
:next_appointment,
-> { where("appointment_date >= now()").order(:appointment_date).limit(1) },
class_name: "::Appointment",
foreign_key: :patient_id
)
scope :by_range_next_appointment_date, lambda { |from, to|
where(...)
}
end
現在我想創建一個范圍,回傳在給定范圍內進行下一次約會的所有患者。我怎樣才能填寫where()來完成這個?
這里有一個例子來說明:
假設 Bruce Banner 的約會時間為 11/2/2021,而 Peter Parker 的約會時間為 10/27/2021 和 11/3/2021。現在我希望這個范圍回傳所有在 11/1/2021 和 11/7/201 之間預約的患者(截至 2021 年 10 月 26 日)。這應該只會回傳 Bruce Banner,因為他的下一次約會在該范圍內。彼得帕克的下一次約會是明天,所以他不應該被包括在內。
uj5u.com熱心網友回復:
由于appointment_date位于另一個表中,.join因此需要 a 來訪問此列。可以通過簡單地將 a 傳遞Range給散列引數來查詢一系列值where(它將使用BETWEEN運算子生成 SQL 子句)。
scope :by_range_next_appointment_date, lambda { |from, to|
joins(:appointments).where(appointment_date: from..to)
}
這應該回傳在給定日期范圍內有預約的所有患者。如果您只想要未來的約會 - 您可以鏈接其他.where.
scope :by_range_next_appointment_date, lambda { |from, to|
joins(:appointments)
.where(appointment_date: from..to)
.where("appointment_date >= now()")
}
要小心傳到型別的值.where-轉換Date價值與.to_datetime如果列型別datetime。
uj5u.com熱心網友回復:
您應該能夠joins在下一次約會時檢查該記錄是否包含在該范圍內。
scope :by_range_next_appointment_date, lambda { |from, to|
joins(:next_appointment).where(appointments: { appointment_date: from..to } )
}
您需要appointments在where子句中使用,因為這是表名,但它只會檢查next_appointment
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338269.html
