AllenC
AllenC

Reputation: 2754

Having a duplicate number sequence in slug using FriendlyId

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.

Upvotes: 0

Views: 242

Answers (2)

AllenC
AllenC

Reputation: 2754

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

Upvotes: 0

cschroed
cschroed

Reputation: 6899

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

Upvotes: 1

Related Questions