Ruby on Rails Thursday, July 13, 2017

On Tuesday, 11 July 2017 09:33:05 UTC-4, Ralph Shnelvar wrote:
Let's say I expect to have a billion users in my Postgres users table.

I want to make sure the first user gets to set it's role attribute to enum :admin as the default when the record is created and all other users are enum  :user.

Of course a billion users is ridiculous.  I'm just trying to understand what the, uh, best way to see if a Postgres table is empty without actually having to load it.

I suspect `User.exists?` is going to be the lightest possible option. `User.count == 0` will also work, but I know there are some DBs where that operation can be expensive on large tables.

This is still going to do a query every time it checks, so if that's too much load you could cache the result:

class User < ActiveRecord::Base
  def self.any_users?
    @any_users ||= exists?

Then your role-defaulting code can check `self.class.any_users?`, which will only run one query (per server) that returns true.

NOTE NOTE NOTE: the above is not 100% thread-safe. It assumes that there is exactly one user sending requests trying to be the first. If you're worried about somebody racing to sign up for that first account, you'll want to come up with a more secure approach.

--Matt Jones

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment