简体   繁体   中英

Active Record sorting based through an association

So I have Three Models. Users, Patients, and Calendar Days. Users and have many Patients and Patients can have many Calendar Days.

What I would like to do is pull patients for one user and sort by a column in calendar days.

The tables in the db are setup normally how you would do it in rails with ids that ActiveRecord uses to associate in the models (and associations are setup correctly).

Example: The user bob@example.com has 4 patients (Tom, John, Sally, and Jane). Each patient has a calendar day for today and yesterday (Calendar days are unique for each date).

I would like to pull all four patients and sort by today's created_by date (The date column is really a datetime field, which is really sorting by today's time).

I've been trying to something together like @patients = user.patients.order(.join(:calendar_days).order("date DESC")), but I'm not sure how to create and ActiveRecord query that advanced.

I don't think I've ever setup a complicated query like this before.

@jizak almost had it, but you want to limit it to use the current calendar date. You can use a class method to make this easier:

class Patient < ActiveRecord::Base
  has_many :calendar_days

  def self.for_date(date)
    joins(:calendar_days).where('DATE(calendar_days.created_at) = ?', date) 
  end
end

user.patients.for_date(Date.today).order('calendar_days.created_at DESC')

Note that the 'DATE(...)' function used in the where condition is MySQL and SQLite specific and won't work for PostgreSQL or Oracle - they have other ways of doing the same thing.

You can do like this

u.patients.joins(:calendar_days).order('calendar_days.created_at DESC')

Or you can add .select to fecth specific fields

u.patients.joins(:days).select('patients.*, days.name as days_name').order('days.created_at ASC')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM