Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.


Sorted and Translated ActiveRecord Model with Globalize2 and Ruby Magic

This code returns all records of your model sorted by translated field name when using Globalize2 :

app/models/widget.rb def self.all_sorted Widget.find(:all, :joins => :globalize_translations, :conditions => ['locale = ?', I18n.locale]).sort_by(&:name) end

As outlined it this post, :joins => :globalize_translations is mandatory. The unary ampersand operator converts a Proc to a block, so in this case sort_by(&:name) is ?shorthand? for

sort {|x,y| x.name <=> y.name}

Ruby sometimes feels like assembling a Swiss watch in code, where other languages feel like fixing an old car.