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)
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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