I'm trying to customize my show route... I don't want users to be able to view items by :id...
I have a sales model, and the show route is:
sale GET /sales/:id(.:format) sales#show
But, I don't want users to be able to view sales by id, instead, I'd like it to be:
sale GET /sales/:guid(.:format) sales#show
The guid is a uuid I generate when the object is created:
def populate_guid
self.guid = SecureRandom.uuid()
end
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to resources can declare all of the necessary routes for your index , show , new , edit , create , update , and destroy actions.
Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.
Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
In config/routes.rb
get '/sales/:guid', to: 'sales#show'
or if you use rails 4 you may:
resources :sales, param: :guid
In controller
def show
@sale = Sale.find(params[:guid])
end
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 find the sale you want from the guid
that was passed in the url:
def show
@sale = Sale.find_by_guid(params[:guid])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With