问题描述
我有一个有_many :admissions 的患者模型.我想为患者模型创建一个范围,该范围将返回当前入院的所有患者.如果患者的任何入院时间为 nil,则确定该患者入院.通过遍历患者并检查每次入院,我可以在应用程序中轻松完成此操作,但似乎我应该让数据库来执行此操作.我以前没有写过这样的范围.有什么建议么?(我在开发中使用 sqlite3,在生产中使用 postgresql,以防需要一些 SQL - 我希望不是)
I have a Patient model that has_many :admissions. I want to create a scope for the patient model that will return all patients that are currently admitted. A patient is determined to be admitted if any of their admissions has a discharge_time of nil. I can do this easily enough in the app by iterating through the patients and checking each admission but it seems like I should be getting the database to do this. I haven't written a scope like this before. Any suggestions? (I'm using sqlite3 in development and postgresql in production in case some SQL is necessary - I hope it isn't)
推荐答案
class Patient < ActiveRecord::Base
has_many :admissions
scope :admitted, includes(:admissions).where('admissions.discharge_time' => nil)
end
你也可以做这样的事情,我认为这有点干燥:
You can also do something like this which I think is a little DRYer:
class Admission < ActiveRecord::Base
belongs_to :patient
scope :active, where(:discharge_time => nil)
end
class Patient < ActiveRecord::Base
has_many :admissions
def self.admitted
joins(:admissions) & Admission.active
end
end
这篇关于如何编写范围来搜索嵌套模型上的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!