Custom ID’s for ActiveRecord
Announcing has_public_id
Today I wrote a very simple plugin to generate unique, random alphanumeric codes with model-specific prefixes for any and all ActiveRecord models.
Lets go straight for a code example:
Why do this, you ask?
A few reasons. First, we wanted keys that were more friendly for our API. By prefixing a few characters on each key we can easily identify what model it belongs to. I first saw this type of key on the Stripe API and found it really helpful in implementation and debugging.
We also prefer to use keys like this in our URLs, and anytime we refer to these models.
Additionally we felt that exposing our monotonically increasing database primary keys in our public API’s was more information than we wanted to share about the size of our tables, the ordering of our records and the underlying implementation details. Check it out on github: has_public_id
I’d love to see more API’s pick up this style of key generation, so hopefully some people will find this useful.
Just don’t forget to index your new columns.









