Accepting only POST for controller actions in Rails

While hammering code out for my new project, I needed to code up a controller which are to be called by external services. Since GET has its own inherent troubles, I decided to only limit POST request to the controller actions.

I started using request.post? check in all my controller actions. Pretty tedious and its not DRY at all.

I digged a little more and found out that there's a verification mechanism that is built into Rails. Cool !

 

First, you will have to put the verify chunk right after your controller, like this

  verify :method => :post,

         :render => {:action => :error},

         :except => :error

What I am doing here is that, I want all my controllers to handle only POST request. And when a GET request comes in, Rails will render the action called error. You will then have to put an error page in your views for this controller. Finally, I'm telling Rails to run this rule for all the controller actions except the error action (which makes sense since you will probably be doing a GET to the error page)

 

Oh yeah, you will need to an extra route to your routes.rb file so that Rails can find your controller actions.

 

 

Posted 5 months ago

1 comment

May 30, 2010
andmej said...
Another thing you could do is add :conditions => { :method => :post } to your routes.rb file.

Example:
map.add_to_cart "/cart/:user_id/add", :controller => "cart", :action => "add", :conditions => { :method => :put }

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     twitter