ActiveRecord Find All not sorting by ID?

前端 未结 5 1001
梦如初夏
梦如初夏 2020-12-03 13:55

I\'ve got a strange issue on a Heroku deployment that I can\'t seem to duplicate locally. Basically when I find all on a specific model instead of sorting by ID it seems to

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 14:23

    You should explicitly order your queries. Usually, there's no guaranteed or fixed order provided by the database.

    Also, you should not use default_scope (see: 1, 2, 3). Use a normal scope or explicit ordering instead:

    class Model < ApplicationRecord
      scope :oldest_first { order(created_at: :asc) }
    end
    
    Model.oldest_first.limit(10)
    Model.order(created_at: :desc).limit(10)
    

提交回复
热议问题