Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails – Custom Resource Routes

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
like image 895
cmw Avatar asked Nov 02 '13 21:11

cmw


People also ask

What are Rails resource routes?

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.

What is the difference between resources and resource in Rails?

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.

How do I find a specific route in Rails?

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.


2 Answers

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
like image 158
mike90 Avatar answered Oct 26 '22 10:10

mike90


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
like image 31
jvperrin Avatar answered Oct 26 '22 08:10

jvperrin