Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use ulid_with_prefix()? #5

Closed
airblade opened this issue Oct 12, 2023 · 4 comments
Closed

How to use ulid_with_prefix()? #5

airblade opened this issue Oct 12, 2023 · 4 comments

Comments

@airblade
Copy link

Hello!

I wasn't quite sure where to ask this question – hopefully this is the right place :)

I am using this extension with Rails via this mechanism so I can use ULIDs for my primary keys as described here.

It works perfectly when I use the plain ulid() function like this in a Rails database migration:

create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID()" }
end

However I would like to have prefixed ULIDs, e.g. thing_01hcj2c9q1kfe2ny0z3957y18v. I tried to modify the migration like this:

create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID_WITH_PREFIX('thing')" }
end

But this raised the error SQLite3::SQLException: invalid BLOB input to ulid().

Do you have any tips for fixing this please?

@airblade
Copy link
Author

cc @fractaledmind :)

@airblade
Copy link
Author

Oops, never mind, it works perfectly. I had a typo in the function name. Doh.

@fractaledmind
Copy link

Glad you got this sorted. You should write up your setup and share it. I'd love to read how you are using prefixed primary key ULIDs and what the experience has been like.

@airblade
Copy link
Author

create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID_WITH_PREFIX('thing')" }
  t.belongs_to :widget, null: false, foreign_key: true, type: :string
end

All in all, a straightforward and painless process :)

My only previous experience with prefixed IDs was using @excid's prefixed_ids gem on a Rails app with postgresql. That worked well, though it needs to inject code into your models, and your application code needs to be at least slightly aware of it, e.g. special finders.

Comparing the two approaches, I much prefer having the database, rather than the model, handle ID generation. My application code doesn't have to know anything about the models' IDs. It's much simpler. (And ULIDs seem at least as good as hashids, if not better, for my purposes.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants