Rails - Custom Resource Routes

I am trying to customize my display route ... I do not want users to be able to view items by: id ...

I have a sales model, and the delivery route:

sale GET /sales/:id(.:format) sales#show 

But I don’t want users to be able to view sales by id, instead I would like to:

 sale GET /sales/:guid(.:format) sales#show 

The guide is the uuid that I generate when the object is created:

 def populate_guid self.guid = SecureRandom.uuid() end 
+6
source share
2 answers

In config / routes.rb

 get '/sales/:guid', to: 'sales#show' 

or if you use rails 4, you can:

 resources :sales, param: :guid 

In the controller

 def show @sale = Sale.find(params[:guid]) end 
+9
source

You can define a custom route in your routes. rb:

 get "/sales/:guid", :to => "sales#show" 

And then in your controller for the show action you will find the sale you want from guid , which was passed in the URL:

 def show @sale = Sale.find_by_guid(params[:guid]) end 
+1
source

Source: https://habr.com/ru/post/957263/


All Articles