norman / friendly_id

FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.
http://norman.github.io/friendly_id/
MIT License
6.13k stars 589 forks source link

Generate slug with a `name` and `id` of the record #1008

Open GabrielLyonB opened 1 year ago

GabrielLyonB commented 1 year ago

I want to generate the the slug with the name column and the id. So i set the slug_candidates like this:

def slug_candidates
  [
    [:name, :id]
  ]
end

The problem here is that the slug is set before the record is created. So when the slug is created the id is not yet set. I created an after_create custom method to unset the slug and then save again to regenerate the slug.

after_create :custom_set_slug

def custom_set_slug
  # skips validations on pourpose, so when is called the save method it sets the proper slug
  update_column(:slug, nil)
  save!
end

Is there a better way to do this?

sergiotapia commented 2 months ago

I have this exact same use case.