Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friendly ID slug does not contain the id

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.

like image 779
Besi Avatar asked Jan 06 '23 17:01

Besi


1 Answers

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
like image 93
Terry Raimondo Avatar answered Jan 16 '23 00:01

Terry Raimondo