2016-08-16 68 views
0

我想爲我的Rails應用程序中的模型創建一些新的訂單方法。這種順序方法應該能夠比較一列中的記錄。在列表的開頭應該是該列最高(> 250)和最低(< 80)值的記錄,其他值(平均值在80和250之間)應該在列表末尾。是否有可能在軌道中做到這一點?Rails是否可以爲模型創建自定義的訂單方法?

+0

如果發生這種情況由於性能原因數據庫/ SQL中或你想一個普通的紅寶石的解決方案? – slowjack2k

+0

在SQL內部沒問題,但是如果你可以給我一個提示,如何用普通的紅寶石做這樣的事情,那會很棒。 –

回答

0

隨着平原紅寶石

# when order between 0 - 80 and > 250 does not matter 
YourModel.all.to_a.sort_by do |record| 
    if record.order_col < 80 || record.order_col >250 
    0 
    else 
    1 
    end 
end 

# when order between 0 - 80 and > 250 does matter 
YourModel.all.to_a.sort_by do |record| 
    if record.order_col < 80 || record.order_col >250 
    record.order_col 
    else 
    record.order_col + YourModel.max(:order_col) + 1 
    end 
end 

隨着SQL

# with sql 

scope :ordered, find_by_sql(%(
    SELECT your_model.* FROM your_model where value < 80 OR value > 250 ORDER BY id desc 
    UNION 
    SELECT your_model.* FROM your_model where value >= 80 and value <= 250 ORDER BY id desc 
)) 

# can work with mysql 
YourModel.select(:field, ..., 'IF (column < 80 OR column > 250, column, column + (SELECT max(column) FROM yourtable) + 1) as order_column').order('order_column desc') 
相關問題