Saturday, May 26, 2007

order column in a model causes problems




Here's a little problem I ran into with Ruby on Rails recently, I figured it out and wanted to share it with you:

I had a model where I was doing a :has_many with a model that I wanted to order by a column that I named "order", it looked like this:


class CreateProgramExercises < ActiveRecord::Migration
def self.up
create_table :program_exercises do |t|

t.column :position, :integer

end
end
end



class Program < ActiveRecord::Base

has_many :program_exercises, :order => "order"
has_many :exercises, :through => :program_exercises

end




When I tried to test this, I got the following error:


3) Error:
test_spec {General tests} 003 [ProgramExercises should be ordered by order column](General tests):
ActiveRecord::StatementInvalid: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1: SELECT * FROM program_exercises WHERE (program_exercises.program_id = 1) ORDER BY order


It turns out that you can't call a column that you want to order "order", you have to call it something else, so I just changed the name to "position" and it worked.

(n.b. I had first changed it to the next logical name "index" but MySQL didn't like that either)