I want to have urls like this:
http://domain.com/products/454-table-lamp
So I use friendly_id like so:
extend FriendlyId
friendly_id :slug_candidates, use: :history
def slug_candidates
[
[:id, :title]
]
end
Now, since friendly id generates the slug before the object is saved I end up with an url like so (Please note the missing id in the URL):
http://domain.com/products/table-lamp
Now while this is not too bad as such. As soon as I save another Product called "Table Lamp", I will get an URL like this:
http://domain.com/products/table-lamp-ebaf4bf5-a6fb-4824-9a07-bdda34f56973
So my question is, how can I make sure, friendly ID creates the slug containing the ID as well.
Just add an after_commit callback to your model. In this callback, set slug to nil and save:
after_commit :update_slug, on: :create
def update_slug
unless slug.include? self.id.to_s
self.slug = nil
self.save
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With