Reputation: 15492
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.
Upvotes: 3
Views: 4054
Reputation: 211540
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')
Upvotes: 4
Reputation: 94113
You could also use the Symbol
to Proc
shorthand available in rails, along with Enumerable#sort_by
to simplify your sort statement, if you want to sort after collecting ActiveRecord objects:
@items.sort_by(&:created_at)
# is the same as @items.sort{ |a, b| a.created_at <=> b.created_at }
Upvotes: 5
Reputation: 52316
You should be able to do one of these:
Sort when accessed:
if type == 1
@items = mycompany.items(:order => 'created_at')
else
@items = myhome.items(:order => 'created_at')
end
Sort after accessing:
@items.sort{|a,b| a.created_at <=> b.created_at}
Upvotes: 6