Keep an eye on your ordered assumptions

31 May

A nasty bug on ZED9 I’ve been avoiding the past few days was solved with a stupid single line.

In Rails, when you have a has_many relationship, it’s great and easy to be able to iterate through all the items. Assume you have models as such

class Foo < ActiveRecord::Base
    has_many :bars
end

class Bar < ActiveRecord::Base
    belongs_to :foo
end

So you go ahead and iterate through them:

@foo = Foo.find(:last)
@foo.bars.each {|f| f.your.logic.here}

If for anyreason, you’re counting on the ordering of those items, watch out! I was iterating through GPS coordinates, comparing them with the first one. SQL databases make no promise on ordering if you don’t ask for it, and every now and then I was getting totally insane results. Turns out the DB was feeding me the GPS coordinates in reverse order sometimes.

Luckily, rails makes this very easy. Just specify your ordering in the model:

class Foo < ActiveRecord::Base
    has_many :bars, :order => 'time ASC'
end

With that one line, I fixed half a dozen outstanding bugs. Mostly posting so I’m not stupid in the future.

Sphere: Related Content

  • looks like your formatting got foobar'd. I'm assuming you meant :order => 'time ACS'
  • Good catch - looks like the wordpress smilies formatting was messing up the code. Disabled and now fixed.
    thanks!
blog comments powered by Disqus