简体   繁体   中英

Order users in database, so I don't have to do order_by each time I query

Can I order my users in the database, so I don't have to say order_by("created_at desc") each time I query?

Sounds for me like a logical thing to do, but I don't know if it's possible and if it's best practice?

SOLUTION

I'm already using the default_scope and as I understand it from you, it is the best way to do it? Thanks a lot for the answers though.

If you are after results sorted by create date desc , the reverse natural order will be close to this (but not guaranteed to be identical).

If you want a specific ordering, adding order_by() to an indexed query is the best way to assure this.

If you are using the default generated ObjectIds the first 4-bytes are actually a unix timestamp (seconds since the epoch) .. and the _id field is indexed by default aside from a few exceptions noted in the documentation.

So a query like last 50 users created (based on ObjectId) in the mongo shell would be:

db.users.find().sort({_id:-1}).limit(50)

There are mixed views about default scopes, but to achieve what you're asking:

http://apidock.com/rails/ActiveRecord/Base/default_scope/class

class User < ActiveRecord::Base
  default_scope order('created_at DESC')
  ### other model code here ###
end

you should be able to add an index or indexes to your db table. Be careful with running this on a live system as the overhead for creating an index on a large table can be disabling.

EDIT: should have expanded.

By creating an index, you will still have to order, but your ordering/sorting will be more efficient.

ref: Is it okay to add database indexes to a database that already has data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM