Question

I'm using friendly_id and rails 3.2. I'm trying to convert a products table to have clean urls. I'm having no issues using the new slug column, and urls are generating fine like

example.com/products/new-friendly-url

The problem I am running into, is I still want to keep the unique id from active record, or some other unique identifier. The reason being, is that many product might have the same friendly title. If I have a product that has the exact same title, the current behavior is generating a slug with some unique identify already such as:

example.com/products/new-friendly-url--2

So friendly_id is generating unique slugs, but I'm just trying to change the format and not sure where/how to do that.

Is there a way to remove the extra --, and just have one "-" that friendly_id is adding?

Here is my model

       class Product < ActiveRecord::Base
       extend FriendlyId
       friendly_id :title, :use => :slugged

       attr_accessible :description, :image, :posted_by, :title, :url,       
       :price

       validates_format_of :price, :with => /^[0-9]+$/

       belongs_to :user
       has_many :comments
Was it helpful?

Solution

You can change the sequence seperator in configurations of friendly-id.

class Product < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title do |config|
    config.use :slugged
    config.sequence_separator = ":"  
  end 
end

The action that changes the seperator to '-' is not suggested. The document says:

The string used to separate a slug base from a numeric sequence.

By default, -- is used to separate the slug from the sequence. FriendlyId uses two dashes to distinguish sequences from slugs with numbers in their name.

You can change the default separator by setting the sequence_separator configuration option.

For obvious reasons, you should avoid setting it to “-” unless you're sure you will never want to have a friendly id with a number in it.

http://norman.github.io/friendly_id/4.0/FriendlyId/Slugged/Configuration.html#sequence_separator-instance_method

If you can use Rails 4, you can upgrade friendly-id to 5.0, it solves this automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top