rails has many association get latest record based on enum

I have a model as:

class Patient < ActiveRecord::Base
  has_many :patient_statuses
end

Another model as:

class PatientStatus < ActiveRecord::Base
  belongs_to :patient

  enum status: [:registered, :pending, :check_up, :admitted, :discharged]
end

Now, I want to get all the Patient whose last status is admitted

Answers


I think could do something like this:

class Patient < ActiveRecord::Base
  ... 
  has_one  :current_status, -> 
    { order(created_at: :desc).limit(1) }, class_name: 'PatientStatus'

  ...
  def self.admitted
    includes(:current_status).where(
      patient_statuses: { status: 'admitted' }).references(:current_status)
  end
end

You would call this scope method like this:

Patient.admitted

You could also create a scope that accepts an argument and get Patients based on any status:

def self.with_status(status)
  includes(:current_status).where(
    patient_statuses: { status: status }).references(:current_status)
end

Patient.with_status('admitted')

Note that this code is provided as an example and might require some tweaking because of your enum attribute.


Please try this:

ids = PatientStatus.group('user_id', 'id').having('created_at = MAX(created_at)').where(status: :admitted).map(&:user_id).uniq
patients = Patient.where(id: ids)

Need Your Help

iOS Use Current Location Permission dialog is shown twice in Phonegap app

javascript ios cordova geolocation

I have a Phonegap app. I am including cordova.js in the HTML (but not in the www directory), I am waiting for deviceready to be fired, and then I'm calling

get UDID of IOS device programmatically?

ios objective-c iphone udid

I want to get UDID of iOS device programmatically. I am using the following code to get UDID of iOS device.