I am very new to friendly_id and it matches my need to provide friendly URLs
I have a Group model (i.e. a group of users) for which I generate a unique code upon creation. FYI, this code attribute is set as a unique index in my PostgreSQL database.
class Group < ApplicationRecord
include FriendlyId
friendly_id :code
after_create :generate_group_code
private
def normalize_friendly_id(value)
super.upcase
end
def generate_group_code(size = 8)
allowed_chars = ("a".."z").to_a
code = (1..size).map { allowed_chars[rand(26)] }.join while Group.exists?(code: code)
update(code: code)
end
end
I think I have followed the gem's guide properly, I just want the generated code to be upcased in the URLs (i.e. /group/ABCDEFGH).
The friendly_id is indeed set as my code attribute, but it is not upcased. I placed a byebug in the normalize_friendly_id method but it is never triggered. What am I missing?
Sunny's way is probably the way to go in general, as the
sluggedmodule is required to edit internal methods such asnormalize_friendly_id.In my case, I already have a
codeattribute that is unique. Using thesluggedmodule would create a new attribute calledslug, which would be exactly the same as mycode. I want to avoid that duplication.In the end, I decided to dodge the
friendly_idgem and directly override theto_parammethod the my model (inspired by this gist):I'll edit this answer if I encounter any side effect, but for now it works.