2009-06-23 21 views
3

ruby​​/rails是否有可能在查找後對結果集進行排序?例如,是否有可能做這樣的事情你可以做一個:在發現後的紅寶石命令?

警告:不工作

if type == 1 
    @items = mycompany.items 
else 
    @items = myhome.items 
end 

@items = @items :order => "created_at" 

我會承擔這樣的事情應該是可能的,但我仍然很新的回報率和能谷歌似乎沒有發現任何東西。訪問時

排序:

回答

4

我不知道爲什麼每個人都是「不行」,只要有可能在命名範圍內。

例如,定義爲的ActiveRecord :: Base的一部分:

named_scope :by_created_at, :order_by => 'created_at' 

這使您可以轉換成一個有序的一個簡單的關係之前,它實際上是檢索:

@items = @items.by_created_at 

作爲請注意,包含有重疊的範圍並不是一個好主意:訂單定義,因爲這會導致它們被附加,而不是依次重複。

然而,在你的榜樣它不是一個太大的舒展的想象重構它,如下所示:

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

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

你應該能夠做到其中的一個訪問後

if type == 1 
    @items = mycompany.items(:order => 'created_at') 
else 
    @items = myhome.items(:order => 'created_at') 
end 

排序:

@items.sort{|a,b| a.created_at <=> b.created_at} 
5

您也可以使用Symbol to Proc shorthand提供軌道,以及Enumerable#sort_by以簡化您的排序聲明,如果您想在收集ActiveRecord對象後排序:

@items.sort_by(&:created_at) 
# is the same as @items.sort{ |a, b| a.created_at <=> b.created_at }