Sort array returned by ActiveRecord by date (or any other column)

前端 未结 5 1260
南方客
南方客 2020-12-22 23:34

How can I sort an array returned by an ActiveRecord query by a created_at date column?

This occurs once the query has been executed.

Please don

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 00:18

    While Ruby Enumerable is awesome, ActiveRecord queries will actually return an ActiveRecord::Relation whose query will not have been evaluated yet (Lazy Loading) and can have the order method called on it to off-load this processing to the database where it will scale much better than an Enumerable based strategy.

    Using Enumerable for sorting also confounds doing pagination in the database. There is nothing to prevent the order strategy from being applied in the view. However, I would tend to put this in scope on the model.

    sorted = @records.order(:created_at)
    

提交回复
热议问题