Ordering on a Field in a Linked Table

I attempted to order my runners based on their assigned stage number. The stage number is linked by the stage_id in the schema and the class shows that it belongs to a stage:


class Runner > ActiveRecord::Base
  belongs_to :stage
end

At first glance, I figure I would simply order on the stage number:


def self.find_all_runners
  find ( :all, :order => "stage.number" )
end

But this resulted in a “no such column” error:

SQLite3::SQLException: no such column: stages.number: SELECT * FROM “runners” ORDER BY stages.number

I found the solution in Ryan Daigle’s blog. In order for this to work you need a :joins to the linked table so Active Record knows the origin of stage.number. In my application, the find should be:


def self.find_all_runners
  find ( :all, :joins => :stage, :order => "stages.number" )
end

This entry was posted in Computers, Programming and tagged , . Bookmark the permalink.