Using Number Sequence for Duplicate Slugs [Friendly ID]

I noticed in the docs :Previous versions of FriendlyId appended a numeric sequence to make slugs unique, but this was removed to simplify using FriendlyId in concurrent code.

Is there a way to get back to this format? My model only has name

, so there are no other viable bullet candidates, and ( time

or date

doesn't make sense in this case for bullet candidates).

How can I change this (current format):

car.friendly_id #=> "peugeot-206"
car2.friendly_id #=> "peugeot-206-f9f3789a-daec-4156-af1d-fab81aa16ee5"
car3.friendly_id #=> "peugeot-206-f9dsafad-eamj-2091-a3de-fabsafafdsa5"

      

In it:

car.friendly_id #=> "peugeot-206"
car2.friendly_id #=> "peugeot-206-1"
car3.friendly_id #=> "peugeot-206-2"

      

-1


source to share


3 answers


The old behavior was implemented in a custom module . But at the moment it hasn't been released yet. So, if you want to restore the old behavior, you can switch friebdly_id

to Gemfile

on Github and add sequentially_slugged

to the list of modules.



+1


source


I understand what you said

(time or date will not make sense in this case for list candidates)

But on the assumption that we only mean the string time format and not unix, which is a numeric sequence, I came up with this workaround for your problems / problems:

  • your model only has a name attribute
  • you cannot use id to add to slug because it hasn't been created yet
  • you want the bullets to be uniq and up
  • you don't want to use UUID



# app/models/car.rb
class Car < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged

  def normalize_friendly_id(string)
    incremented_number = (Time.now.to_f * 1000000).to_i
    "#{super}-#{incremented_number}"
  end
end

      

So now it works

car1 = Car.create(name: "peugeot")
car2 = Car.create(name: "peugeot")
car3 = Car.create(name: "peugeot")

car1.friendly_id #=> "peugeot-1451368076324115"
car2.friendly_id #=> "peugeot-1451368076457560"
car3.friendly_id #=> "peugeot-1451368076460087"

      

Note: numbers increase

Time.now.to_f * 1000 will be miliseconds and I am using Time.now.to_f * 1000000 which MICROSECONDS <is one millionth of a second. It will NOT be created at the same time and therefore will not encounter conflicts in the slug. And if someone there thinks that then he can add a few more zeros to this factor.

0


source


There are good reasons why the "serial number" has been replaced by the UUID (race conditions).
I usually use an additional pool candidate with an ID which is supported by uniq db and is much shorter than the UUID:

[ [:name], [:name, :id] ]

      

-1


source







All Articles