0

I'm using the gem 'friendly_id', '~> 5.0.0 and I just want to use the old behaviour which is appending a number sequence count in the slug instead of UUID.

for example

>> test-slug-2
>> test-slug-3
>> test-slug-4

I was able to make this using: config/initializers/slugged.rb

module FriendlyId::Slugged
  def resolve_friendly_id_conflict(candidates)
    column = friendly_id_config.slug_column
    separator = friendly_id_config.sequence_separator
    slug = normalize_friendly_id(candidates.first)
    sequence = self.class.where("#{column} like '#{slug}#{separator}%'").count + 2
    "#{slug}#{separator}#{sequence}"
  end
end

and in my model

  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders]

However when I have a test-slug-3 and test-slug-4 and tried to delete the test-slug-3 the next time I create a record it will generate a slug which is test-slug-4 which is having an error in my end because Slug is already taken.

AllenC
  • 2,754
  • 1
  • 41
  • 74

2 Answers2

1

One option would be to use the substring method to find the max number. For example, in PostgreSQL you could do something like:

slug_start = "#{slug}#{separator}"
sequence = self.class.where("#{column} like '#{slug_start}%'").maximum("SUBSTR(#{column}, #{slug_start.length + 1})::Int") + 1
cschroed
  • 6,304
  • 6
  • 42
  • 56
  • Thanks @cschroed however I'm using mysql my workaround for this is getting the maximum id of the similar slug and add +1 and appends the the slug that will be created. – AllenC Feb 05 '15 at 03:13
0

Anyway I make a workaround for this. If slug is already taken the next time you create a slug it will get the maximum id of the similar slug and add +1 and appends to the next slug you will create.

Here's my code:

 def resolve_friendly_id_conflict(candidates)
    column = friendly_id_config.slug_column
    separator = friendly_id_config.sequence_separator
    slug = normalize_friendly_id(candidates.first)
    count = self.class.maximum("id") + 1 || 1
    if self.class.where("#{column} like '#{slug}%'").count >= 1
      "#{slug}#{separator}#{count}"
    end
  end
AllenC
  • 2,754
  • 1
  • 41
  • 74