ActiveRecord Find All not sorting by ID?

前端 未结 5 1025
梦如初夏
梦如初夏 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:47

    In SQL, tables are considered to be sets of records, not lists of records, and a 'select' query is not guaranteed to return records in any particular order unless an 'order by' clause is specifically included. You may happen to see that results come back in a particular order sometimes, but that doesn't mean you can or should assume it will always be so.

    Using ActiveRecord, you can force a default 'order by' clause if you like by specifying a default scope. In general, that's a bad idea though, because it will force the server to do more work to give you a sorted result set, even when you don't need it sorted. Furthermore, sorting in the 'id' field is usually inappropriate, since the point of 'id' is to be an opaque record identifier with no purpose or meaning other than to be unique for a given record in a table.

提交回复
热议问题