I have project with Rails 4.1. I need to implement url something like this .../items/. I know I can make it manually, but I'm too lazy for it.
Does everybody know how can I use friendly_id to get UUID for slug?
Thanks for answers.
I have project with Rails 4.1. I need to implement url something like this .../items/. I know I can make it manually, but I'm too lazy for it.
Does everybody know how can I use friendly_id to get UUID for slug?
Thanks for answers.
You need to override the to_param
method in the Item model and return the UUID of the instance.
The default to_param
method returns the id of the object.
friendly_id
friendly_id
basically just replaces your :id
parameter with a :slug
in the .find
method for ActiveRecord. I think what you're asking is if you wanted to use the :uuid
attribute for your lookups, you'll need to something like the following:
#app/models/your_model.rb
Class YourModel < ActiveRecord::Base
friendly_id :uuid, use: [:slugged, :finders]
end
This will allow you to perform the following:
#config/routes.rb
resources :your_controller #-> domain.com/your_controller/:id
You'll be able to pass in your :uuid
to the :id
, both through the link_to
method, and in the .find
method too. Apart from that, I don't see what the issue would be?
Follow standard instructions and create slug column for your model.
Add friendly_id to your model:
extend FriendlyId
friendly_id :uuid, use: [:slugged, :finders]
We do not have uuid column for our model, but we can specify method which able to generate it if slug is not set yet.
def uuid
slug || SecureRandom.uuid
end
I arrived here looking for how to use friendly_id with a table that has uuid primary keys.
For me, I was getting this error:
ActiveRecord::StatementInvalid in PostsController#create
PG::UndefinedFunction: ERROR: operator does not exist: integer = uuid LINE 1: ...type" = $1 AND "friendly_id_slugs"."sluggable_id" = "posts".... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
The solution was to rollback the migration (rails db:rollback STEP=1
), then go into the slugs migration and change this line
t.integer :sluggable_id, :null => false
to this
t.uuid :sluggable_id, :null => false
More info here.