简体   繁体   中英

Rails order active record results based on one column and another if null

So I have an active record query that returns some records, lets say it looks like this.

jobs = Job.where(:user_id => current_user.id)

As you would expect this returns the current_user's jobs. Assume that the job has two dates, deadline_date and due_date . If I want to order on deadline_date I can do something like..

jobs.order("deadline_date asc")

That works as expected, now image I have something in the job model like this.

class Job < ActiveRecord::Base
 def deadline_date
  self.read_attribute(:deadline_date) || self.due_date
 end
end

So the job will display its deadline_date if it is not nil else it will fallback to use the due_date . So to sort this I have done the following...

jobs.sort_by{|job| job.deadline_date}
jobs.sort_by{|job| job.deadline_date}.reverse

This solves my problem but I wondered it there were better alternatives, is it possible to achieve this using SQL? Also this produces some repeated code in that I have a sort_order variable in my controllers that I can pass directly like this...

jobs.order(sort_order)

Now it looks more like this...

if params[:sort] == "deadline_date"
 if params[:order] == "asc"
  jobs.sort_by{|job| job.deadline_date}
 else
  jobs.sort_by{|job| job.deadline_date}.reverse
 end
else
 jobs.order(sort_order)
end

Note: This is a arbitrary example in reality it is a bit messy but you get the idea. So I'm looking for an SQL alternative or a suggestion on how it could be improved. Cheers

If I understand you correctly, you should be able to do this using the COALESCE SQL function:

jobs.order(Arel.sql("COALESCE(deadline_date, due_date)"))

That's pretty much the same as deadline_date || due_date deadline_date || due_date in Ruby.

I believe it to be a standard SQL thing, so it should work for most SQL dialects.

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