0

Okay so I'm working on making a friendly_id that allows me to scale it effectively. This is what I got so far. What it does is essentially add +1 on a count if you have a matching name. So if you are the 2nd person to register as John doe your url would be /john-doe-1.

extend FriendlyId
friendly_id :name_and_maybe_count, use: [:slugged, :history] 


def name_and_maybe_count
 number = User.where(name: name).count
 return name if number  == 0
 return  "#{name}-#{number}"
end

However this piece of code is still bringing me some issues.

  • If I have created a user called John Doe. Then register another user called John Doe the slug will be /john-doe-UUID. If I register a third user then it will receive the slug john-doe-1.
  • If I have two users. One that registered with the name first. Say Juan Pablo. Then he changes his name to 'Rodrigo', and then change it back to 'Juan Pablo'. His new slug for his original name will be 'juan-pablo-1-UUID'.

I know this is minor nitpick for most of you but it's something that I need to fix!

sja
  • 347
  • 1
  • 10

1 Answers1

0

You want to overwrite to_param, include the id as the first bit of the friendly id

I extend active record like this in one of my apps,

module ActiveRecord
  class Base
    def self.uses_slug(attrib = :name)
      define_method(:to_param) do
        "#{self.id}-#{self.send(attrib).parameterize}"
      end
    end
end

so I can do

uses_slug :name

in any model but this alone in any model should work:

def to_param
  "#{self.id}-#{self.my_attrib.parameterize}"
end

The benefit of this is that in the controller you when you do

Model.find(params[:id]) 

you don't have to change anything because when rails tries to convert a string like "11-my-cool-friendly-id" it will just take the first numeric bits and leave the rest.

pixelearth
  • 13,674
  • 10
  • 62
  • 110