How to Use Custom IDs with Avo
Avo seamlessly integrates custom IDs, including popular solutions like FriendlyID, prefixed IDs, or Hashids. Below, you'll find examples illustrating each approach for effortless customization within your application.
Example with FriendlyID
FriendlyID is a gem that allows you to generate pretty URLs and unique IDs. To integrate FriendlyID with Avo, follow these steps:
Install friendly_id gem by adding this line to your application's Gemfile:
gem "friendly_id", "~> 5.5.0"And then execute:
bundle installGenerate and run the migration to add a slug column to your model:
rails generate friendly_id
rails db:migrateAdd friendly_id to your model:
WARNING
To enable full compatibility with Avo, you need to use the use: :finders option.
It also can be used as array of options like use: [:finders, :slugged].
# app/models/post.rb
class Post < ApplicationRecord
extend FriendlyId
# This post model have a name column
friendly_id :name, use: :finders
endWith this setup, you can use Post.find("bar") to find records by their custom IDs.
INFO
For a version of friendly_id smaller then 5.0 you can use custom query scopes
View friendly_id setup in action: View Demo
Check out the code: Code on GitHub
Example with Prefixed IDs
Prefixed IDs involve adding a custom prefix to your IDs.
Install prefixed_ids gem by adding this line to your application's Gemfile:
gem "prefixed_ids"And then execute:
bundle installBasic Usage
Add has_prefix_id :my_prefix to your models to autogenerate prefixed IDs:
# app/models/post.rb
class Post < ApplicationRecord
has_prefix_id :post
endView prefixed_ids setup in action: View Demo
Check out the code: Code on GitHub
Example with Hashids
Hashid Rials is a gem that generates short, unique, and cryptographically secure IDs.
Install hashid-rails gem by adding this line to your application's Gemfile:
gem "hashid-rails", "~> 1.0"And then execute:
bundle installInclude Hashid Rails in the ActiveRecord model you'd like to enable hashids:
# app/models/post.rb
class Post < ApplicationRecord
include Hashid::Rails
endView hashid-rails setup in action: View Demo
Check out the code: Code on GitHub
Friendly.rb - Your friendly European Ruby Conference