2015-05-26 82 views
0

我有一個表A(:name, :address, :country_id)。我運行這個查詢排序Rails的活動記錄

ids = [1,2,3] 
@result = A.where(country_id: ids) 

但是,我想要得到結果在這個順序:records containing country_id = 2 first, then 1 and then 3

應該如何我寫這篇文章的查詢?

編輯:

@people = [] 
@result.each do |r| 
    @people.push([r,r.name]) 
end 

我現在@people數組的數組,並希望排序。現在應該是什麼查詢?

另一個編輯:

@people.sort_by! {|p| preferred_order.index(p.first.country_id)} 

這個工作。

+0

需要更多信息:你爲什麼要這樣做?總是有3個結果? – Dan

+0

有很多結果。我想以這樣的順序顯示結果,即包含country_id = 2的行先顯示,然後是1,然後是3 – Hellboy

回答

1

您可以使用sort_by

ids = [1,2,3] 
preferred_order = [2,1,3] 

@result = A.where(country_id: ids) 
@result.sort_by! { |u| preferred_order.index(u.country_id) } 
+0

如果我已將「結果」複製到數組「人員」中,該怎麼辦?我現在應該怎麼做? – Hellboy

+0

請參閱編輯 – Hellboy

+0

然後嘗試'@ people.sort_by! {| u | preferred_order.index(u.country_id)}'讓我知道。 –

0

一個辦法是增加一個額外的列

rails g migration add_sortorder_to_A sort_order:integer 

然後添加一個

before_save :update_sort_order 

def update_sort_order 
    if self.country_id == 1 
    self.update_attributes(sort_order:2) 
    elsif self.country_id ==2 
    self.update_attributes(sort_order:1) 
........ 
end 

或者,把你的排序順序在各國家和排序。

或者,創建一個動態的領域,這將給你的排序順序。

這樣做可能是一種更優雅的方式,但這應該以快速和骯髒的方式工作,並允許您使用標準的activerecord查詢和排序。 (也就是說,一旦你完成了一次,你就可以忘掉它)

+1

另外,請做Sharvy說的話。更優雅... :) – Carpela

+1

請參閱編輯 – Hellboy