Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing default routes for a resource in Rails 3

I have a resource defined like so:

resources :referrals, :except => [:show, :edit, :destroy]

and I'd like to replace (not just add a named route) a default route that Rails produces, specifically the one for the update action.

Here is my rake routes:

referrals    GET  /referrals(.:format)     {:action=>"index", :controller=>"referrals"}
             POST /referrals(.:format)     {:action=>"create", :controller=>"referrals"}
new_referral GET  /referrals/new(.:format) {:action=>"new", :controller=>"referrals"}
referral     PUT  /referrals/:id(.:format) {:action=>"update", :controller=>"referrals"}
share             /share(.:format)         {:controller=>"referrals", :action=>"new"}
special           /special(.:format)       {:controller=>"referrals", :action=>"index"}
thanks            /thanks(.:format)        {:controller=>"pages", :action=>"thanks"}
                  /:shortlink(.:format)    {:controller=>"referrals", :action=>"update"}
                  /:linktext(.:format)     {:controller=>"referrals", :action=>"update"}
root              /(.:format)              {:controller=>"pages", :action=>"home"}

I'd like either the

/:shortlink(.:format)

or

/:linktext(.:format)

to hit the update action, but not the

/referrals/:id(.:format)

This is to implement a form of non-password "security". When the PUT goes to the update action, I want certain things to happen, but I don't want to require authorization to do this, and I don't want to allow easy guessing of the url based on controller name and simple low-numbered ids.

How can I fully replace the default route given by rails?

like image 981
Bodhi Avatar asked Nov 06 '22 00:11

Bodhi


1 Answers

resources :referrals, :except => [:show, :edit, :destroy, :update]

match "/whatever_you_want/:variable_here" => "referrals#updated", :as=> the_link, :via=> :put

then in your controller you will access the param with

params[:variable_here]

here the param is whatever you want to compare against in the db, and the path will be create like this:

the_link_path or the_link_url

the :via part will constrain the path per HTTP method so only put request will match

more info here http://guides.rubyonrails.org/routing.html

like image 124
radha Avatar answered Nov 09 '22 15:11

radha