How do I write a scope to search for attributes on

2019-05-30 01:29发布

问题:

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