rails uuid primary key
Slightly more obscure
- tags
- rails
- uuid
- postgres
Contents
Exposing primary keys externally just sort of invites people to poke around in your system. Lets configure rails to use uuid instead.
Create a postgres rails app
We are going to be relying upon the pgcrypto postgres extension, so
lets go ahead a create a postgres based rails application.
| |
Now we tell our generators that we want our primary key type to be :uuid:
| |
And we need to change the sort order, since when using integer id's
for the primary key rails uses that. We'll tell it to use created_at
instead:
| |
Create your first migration
| |
And make sure that we add to the change method of the migration!
| |
Start postgres and test it out
Lets create a throwaway postgres container to see how things are working
| |
This will delete itself when you close out of it.
We'll need to create a simple config/database.yml file to connect to it:
| |
And then we create and migrate:
| |
And now we can test it out:
| |
The sql for the Post.last command is SELECT "posts".* FROM "posts"
ORDER BY "posts"."created_at" DESC LIMIT $1 which is using the
created_at column.
But this doesn't support sqlite
The uuid column type isn't supported by sqlite. I think it's better
to test on the same database type as production, and with docker it's
easy to throw things up and tear them down, etc. but caveat.
Previously
Next