简体   繁体   English

通过关联对Active Record进行排序

[英]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). db中的表通常是按照在ActiveRecord用来在模型中关联的ID的方式在Rails中进行设置的(并且关联已正确设置)。

Example: The user bob@example.com has 4 patients (Tom, John, Sally, and Jane). 示例:用户bob@example.com有4位患者(Tom,John,Sally和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). 我想拉所有四个患者并按今天的created_by日期排序(date列实际上是datetime字段,它实际上是按今天的时间排序)。

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. 我一直在尝试像@ Patients = user.patients.order(.join(:calendar_days).order(“ date DESC”))这样的东西,但是我不确定如何创建和改进ActiveRecord查询。

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. @jizak几乎拥有它,但是您想限制它使用当前的日历日期。 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. 请注意, where条件中使用的'DATE(...)'函数是特定于MySQL和SQLite的,不适用于PostgreSQL或Oracle-它们具有执行相同操作的其他方式。

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 或者,您可以添加.select来影响特定字段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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