1
votes

I have user resource and model. when I opens user page the url is like /users/:id. It is the default url for show action. But I want something like this --> localhost:3000/8-random-alphanumeric-characters. my routes file:

#for User model
  resources :users
  get 'signup'  => 'users#new'

User resource information,
:id =1

HTTP(Method)  URL      Action   Named route        Purpose
GET          /users        index    users_path         page to list all users
GET          /users/1      show     user_path(user)    page to show user
GET          /users/new     new     new_user_path      page to make a new user (signup)
POST         /users         create  users_path         create a new user
GET          /users/1/edit  edit    edit_user_path(user)   page to edit user with id 1
PATCH        /users/1      update   user_path(user)     update user
DELETE       /users/1     destroy   user_path(user)     delete user

I want /users/1 to be /8-digit-alphanumeric-random-string.

1
you are looking for vanity urls blog.teamtreehouse.com/creating-vanity-urls-in-rails.Saqib
@Saqib I m looking for unmeaningful url's not meaningful.. unmeaningful urls for user show action from user resource ! the default url is localhost/users/:id I want this to be localhost/8-digit-random-string. ever time user open his profile page he gets new random string every time !Nischay Namdev
@T1djani I want random ones ..not short urls!!Nischay Namdev
@Nischaynamdev say you have 2 users how would you distinguish to which user your random url will point. you will have to store and associate your urls to a specific users.Saqib

1 Answers

0
votes

Typically, the URL you're referring to is known as a permalink, so we can start as follows:

First, add a permalink field to your Users table

rails g migration AddPermalinkToUsers permalink:string

(Within the migration you'll want to add an index to this column along with a unique constraint)

Then in your User model, create a before_create callback that generates the permalink for your user

class User < ActiveRecord::Base
  before_create :generate_permalink

  def to_param
    self.permalink
  end

  private 

    # Generates an 8 character alphanumeric id
    def generate_permalink
      self.permalink = SecureRandom.hex(8)
    end 

end

Now tell your routes to adhere to this paradigm

resources :users, param: :permalink

Inside app/controllers/users_controller.rb:

def set_user
  @user = User.find_by(permalink: params[:permalink])
end