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 :


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


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| <=>}

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

[Slashdot] [Digg] [Reddit] [] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Reply