Efficient sorting of rows by multiple columns in Rails 3

这一生的挚爱 提交于 2019-12-24 03:36:33

问题


I have a table name transactions with following columns

created_at        | debit | credit | balance | account_id
2012-2-2 02:22:22 | 3000  | 0      | 0       | 8
2012-2-2 07:22:22 | 500   | 1000   | 0       | 8
2012-2-2 09:22:22 | 0     | 8000   | 0       | 8

2012-3-3 19:17:20 | 1000  | 0      | 0       | 8
2012-3-3 04:02:22 | 0     | 8000   | 0       | 8

Before calculating balance I need to

  • sort transactions by date (i.e. daily)
  • then sort by debit (higher debit must come first)

I have a million transactions distinguished by account_id. What is efficient way of sorting in such a scenario ?

Any answer will be appreciated.


回答1:


This sounds a lot like this question

Transaction.all(:order => "created_at DESC, debit DESC")

This kind of querying is exactly what relational databases are good at and with proper indexing, it should be efficient for you.

For a particular account…

Transaction.find_by_account_id(some_id, :order => "created_at DESC, debit DESC")

If this is setup as a proper ActiveRecord association on the account, you can set the order there so the association is always returned in the preferred order:

class Account
    has_many :transactions, :order => "created_at DESC, debit DESC"
end

This way, any time you ask an account for its transactions like Account.find(12345).transactions they'll be returned in the preferred sorting automatically.



来源:https://stackoverflow.com/questions/14068836/efficient-sorting-of-rows-by-multiple-columns-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!