Can you do an :order in ruby after a find?

activerecord, ruby, ruby-on-rails

Solution

I don't know why everyone's all "No you can't" when it's possible in named scopes.

For example, define as part of ActiveRecord::Base:

named_scope :by_created_at, :order_by => 'created_at'

This allows you to convert a simple relationship to an ordered one before it is actually retrieved:

@items = @items.by_created_at

As a note it's not a good idea to include scopes which have overlapping :order definitions as this causes them to be appended instead of over-riding each in turn.

However, in your example it's not too much of a stretch to imagine refactoring it as the following:

reference =
  case (type)
  when 1
     mycompany
  else
    myhome
  end

@items = reference.items.all(:order_by => 'created_at')

Problem

Is it possible in ruby/rails to order a result set after doing a find? For example, is it possible to do something like this Warning: Does not work ``` if type == 1 @items = mycompany.items else @items = myhome.items end @items = @items :order => "created_at" ``` I would assume something like this should be possible, but I'm still very new to RoR and can't seem to find anything on google.

Original source