cmw
cmw

Reputation: 956

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

Upvotes: 7

Views: 4362

Answers (2)

mike90
mike90

Reputation: 198

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

Upvotes: 11

jvperrin
jvperrin

Reputation: 3368

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

Upvotes: 1

Related Questions