title: Using a SELECT CASE statement in ActiveRecord, as Rails model default_scope
body: <p>I have a model, User, which can either be an individual or a company, depending on the value of a boolean, <code>is_company</code>. If the user is a company, <code>company_name</code> stores the name; if the user is an individual, <code>first_name</code> and <code>last_name</code> stores their name.</p>
  
  <p>In the vast majority of cases, I want the users to be sorted by <code>last_name</code> OR <code>company_name</code> by default, so I'm using a default_scope in my User model.</p>
  
  <p>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?</p>
  
  <pre><code>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')
  </code></pre>
  
  <p>Thanks!</p>