Let´s say I have a model, called Car, and I can access my car show action at /cars/:id
. The first record will live in /cars/1
but I don´t want it. I want the permalink to have a length of 8 numbers, no matter what´s the id of the car. So for example, the first permalink would be 00000001
not 1
.
I don´t know how to implement that, what to do in the model (to_param
method probably) or what to do in the routes.
Please help me if you can, I appreciate any hint.
Have you tried using friendly_id gem. If you can use it and I strongly recommend you use it. From the comments in the code:
FriendlyId always uses a method as the basis of the slug text - not a column. At first glance, this may sound confusing, but remember that Active Record provides methods for each column in a model's associated table, and that's what FriendlyId uses.
Here's an example of a class that uses a custom method to generate the slug:
class Person < ActiveRecord::Base
friendly_id :name_and_location
def name_and_location
"#{name} from #{location}"
end
end
bob = Person.create! :name => "Bob Smith", :location => "New York City"
bob.friendly_id #=> "bob-smith-from-new-york-city"
So, I guess you can do:
class Car < AR::Base
friendly_id :id_of_length_eight
def id_of_length_eight
# logic here to add leading zeroes
end
end