I've add a custom sort to an ActiveRecord model by defining a method like this:
class MyClass < ActiveRecord::Base
belongs_to :parent_model #this would be the many in a has_many relationship
def <=>(other)
self.att <=> other.att
end
end
Suffice it to say, the logic actually being employed in the comparison is a bit more complex than this example, and is not something that can be accomplished with SQL.
Because this class is only used as nested fields in an encompassing model, there doesn't seem to be a straight-forward place to sort the result set. In the controller, :my_class is a part of the include for eager loading, but I don't do anything else with the object array until the view (when I do form.fields_for :my_class). What I really want is to be able to do the equivalent of default_scope using my logical sort, but I don't think that's possible. Right now, my only option seems to be adding an extra line in the controller just to do the sort on this result, but that doesn't seem like it's the right thing to do.
Is there something more elegant I'm missing here?