Cherry
Cherry

Reputation: 1041

How to mask URL rails

I am new to Rails. here trying to replace a word in URL. My routes.rb is:

resources :senders, only: [:index, :update]
 get '/senders/:id', constraints: { :id => /[0-9]+/ }, to: 'senders#show'
 put '/senders/:id', constraints: { :id => /[0-9]+/ }, to: 'senders#update'
 get '/senders/:id/check_status/:ip_index', constraints: { :id => /[0-9]+/, :ip_index => /[0-3]/ }, to: 'senders#check_status'

It shows in the url link as

localhost:3000/senders

but I want it to show as

localhost:3000/receivers

What are the changes I have to make to show receivers/173?

Upvotes: 1

Views: 742

Answers (1)

Kartikey Tanna
Kartikey Tanna

Reputation: 1459

Without changing anything in your controller, you can do the following:

resources :receivers, only: [:index, :update], controller: 'senders'
 get '/receivers/:id', constraints: { :id => /[0-9]+/ }, to: 'senders#show'
 put '/receivers/:id', constraints: { :id => /[0-9]+/ }, to: 'senders#update'
 get '/receivers/:id/check_status/:ip_index', constraints: { :id => /[0-9]+/, :ip_index => /[0-3]/ }, to: 'senders#check_status'

But you should also change your controller name and do the following:

First change your controller name.
Rename app/controllers/senders_controller.rb to app/controllers/receivers_controller.rb

And change the first line in the controller:
SendersController < ApplicationController to ReceiversController < ApplicationController

Then finally, change your config/routes.rb as below:

resources :receivers, only: [:index, :update]
     get '/receivers/:id', constraints: { :id => /[0-9]+/ }, to: 'receivers#show'
     put '/receivers/:id', constraints: { :id => /[0-9]+/ }, to: 'receivers#update'
     get '/receivers/:id/check_status/:ip_index', constraints: { :id => /[0-9]+/, :ip_index => /[0-3]/ }, to: 'receivers#check_status'

You can know more about Rails routing from the documentation.

Upvotes: 3

Related Questions