Skip to content
This repository was archived by the owner on Apr 22, 2025. It is now read-only.

Commit c49b0e2

Browse files
committed
Add Persist module docs
1 parent 1a57ac9 commit c49b0e2

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,39 @@ user = User.create(full_name: "Bob Smith")
144144
Rails.application.routes.url_helpers.user_path(user) # => "/users/bob-smith--p5w9-z27j"
145145
```
146146

147+
### Persisting encoded IDs
148+
149+
You can optionally include the `EncodedId::Rails::Persists` mixin to persist the encoded ID in the database. This allows you to query directly by encoded ID in the database.
150+
151+
To use this feature, you must add the following columns to your model's table:
152+
153+
```ruby
154+
add_column :users, :normalized_encoded_id, :string
155+
add_column :users, :prefixed_encoded_id, :string
156+
add_index :users, :normalized_encoded_id, unique: true
157+
add_index :users, :prefixed_encoded_id, unique: true
158+
```
159+
160+
Then include the mixin in your model:
161+
162+
```ruby
163+
class User < ApplicationRecord
164+
include EncodedId::Model
165+
include EncodedId::Rails::Persists
166+
end
167+
```
168+
169+
The mixin will:
170+
171+
1. Store the encoded ID hash (without character grouping) in the `normalized_encoded_id` column
172+
2. Store the complete encoded ID (with prefix if any) in the `prefixed_encoded_id` column
173+
3. Add validations to ensure these columns are unique
174+
4. Make these columns readonly after creation
175+
5. Automatically update the persisted encoded IDs when the record is created
176+
6. Provide safeguards to prevent inconsistencies
177+
178+
This enables direct database queries by encoded ID without having to decode them first.
179+
147180
## Documentation
148181

149182
### `.find_by_encoded_id`

0 commit comments

Comments
 (0)