Sorted and Translated ActiveRecord Model with Globalize2 and Ruby Magic

Uncategorized Add comments

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.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Reply