How to add id to Friendly_id slug?

231 Views Asked by At

I'm interested in generating slug with both title and id. Otherwise, I would get errors like post collection route overriding single post route.

class Post > ApplicationRecord
  extend FriendlyId
  friendly_id [:id, :title], use: :slugged
end
resources :posts do
  get "videos", on: :collection
end

Slug "videos" would conflict with "videos" collection route.

Is it possible to generate an slug with id and title?

"#{id}_#{title}" # Friendly Id slug
1

There are 1 best solutions below

3
Thanh On

Friendly Id can not do that because it generates slug before save so it will not have id https://github.com/norman/friendly_id/blob/master/lib/friendly_id/slugged.rb#L250

You may need to use to_param method to custom this:

class Post < ApplicationRecord
  def to_param
    "#{id}_#{title}".parameterize
  end
end

But then you need to write custom method to find a record id, something like in your controller:

def show
  id = params[:id].split('_')[0]
  post = Post.find(id)
end