title: In Rails, can I order a query by a delegate method?
body: <p>I'm having difficulty ordering a query by a delegate method. I've been tasked with helping upgrade a fairly large Rails 3 application to Rails 4. I've come across this query in an index action. <strong>I am aware the naming of these objects is horrible and confusing.</strong></p>
  
  <pre><code># measurements_controller.rb
  def index
    @measurements = Measurement.includes(:identifier).order(:name)
  end
  </code></pre>
  
  <p>In Rails 4, I'm getting this error:</p>
  
  <pre><code>ERROR: column info_items.name does not exist LINE 1: ...D (info_item_identifiers.name LIKE '%') ORDER BY "info_item...
  </code></pre>
  
  <p>So I took a look at the models and found:</p>
  
  <pre><code># measurement.rb
  class Measurement &lt; InfoItem
    ...
  end
  
  # info_item.rb
  belongs_to :identifier, class_name: 'InfoItemIdentifier'
  delegate :name, :name=, to: :identifier
  
  # info_item_identifier.rb
  # This object has a name column in the database
  </code></pre>
  
  <p>If I'm in the terminal and I have an instance of a <code>Measurement</code>, I can easily call the <code>.name</code> method and it works great. But when it comes to <code>.order(:name)</code>, that does not work due to the column not existing.</p>
  
  <p>I have found one solution, but it seems to defeat the purpose of the delegate method. In the controller, I can change it to:</p>
  
  <pre><code>@measurements = Measurement.includes(:identifier).order('info_item_identifiers.name')
  </code></pre>
  
  <p>Since I know that <code>InfoItem</code> delegates the <code>name</code> method to <code>InfoItemIdentifiers</code>, I don't think my controller needs to know where it's delegated to.</p>
  
  <p><strong>Is there a way to keep the existing code and still order by the delegate method?</strong></p>