I have a model, User, which can either be an individual or a company, depending on the value of a boolean, is_company. If the user is a company, company_name stores the name; if the user is an individual, first_name and last_name stores their name.
In the vast majority of cases, I want the users to be sorted by last_name OR company_name by default, so I’m using a default_scope in my User model.
However, the way I have it – even though it works for SQLLite – is not database agnostic. Can anyone let me know how I can refactor this to accept a parameter of “true” in the case statement?
default_scope select('users.*')
default_scope select('CASE WHEN is_company = "t" THEN company_name ELSE last_name END AS sort_name')
default_scope order('sort_name ASC')
Thanks!
You might want to do a modest redesign to handle this at the time you write to the database.
display_nameCreate a
before_savecallback in your User model that sets the display name like:Change your default_scope to just order by the new column