Reputation: 2563
In my Rails app, I want to allow my resourceful routes to get the record via either the UUID parameter or the Slug.
Basically I want /users/aafdbc47-b427-4be9-bf4b-4b6c4e9b8303
or /users/sireltonjohn
to work. These are two separate fields in my schema, UUID and Slug respectively. Primarily so I have a non-changing direct link to the user (since the user can change their Slug).
I'm a relative newb to Rails so I'm trying to figure out how, in my routes.rb, to allow that route to work.
Upvotes: 0
Views: 791
Reputation: 3251
Both /users/aafdbc47-b427-4be9-bf4b-4b6c4e9b8303
and /users/sireltonjohn
are routed to users/:id
which is the show
action from UsersController
(if we are following the rails convetions)
Here's a simple way to do it (wrote this from mind)
# app/controllers/users_controller.rb
class UsersController < ApplicationRecord
before_action :find_user, only: :show
def show
p @user
end
private
def find_user
@user = User.where('uuid = :key OR slug = :key', key: params[:id]).first
end
end
# routes.rb
resources :users
You could check friendly_id, see if it suits you.
Upvotes: 1