On Tue, Jul 11, 2017 at 6:33 AM, Ralph Shnelvar <[hidden email]> wrote:
> 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.
Assuming the table is "users" and User is an ActiveRecord model,
(User.count == 0)
However, doing that for every subsequent user creation seems like
a bit of a waste. I would just use the db/seeds.rb file to create that
first admin user and be done with it :-)
Hassan Schroeder ------------------------ [hidden email] twitter: @hassan
Consulting Availability : Silicon Valley or remote
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
@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.