How do I write a scope to search for attributes on a nested model?

喜欢而已 提交于 2019-12-23 02:04:49

问题


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


来源:https://stackoverflow.com/questions/5683735/how-do-i-write-a-scope-to-search-for-attributes-on-a-nested-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!