Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple HTTP methods in the same Rails controller action

Let's say I want to support both GET and POST methods on the same URL. How would I go about handling that in a rails controller action?

like image 718
Kevin Pang Avatar asked Apr 07 '11 15:04

Kevin Pang


2 Answers

You can check if it was a post using request.post?

if request.post?   #handle posts else   #handle gets end 

To get your routes to work:

resources :photos do   member do     get 'preview'     post 'preview'   end end 
like image 129
Jesse Wolgamott Avatar answered Oct 02 '22 10:10

Jesse Wolgamott


Here's another way. I included example code for responding with 405 for unsupported methods and showing supported methods when the OPTIONS method is used on the URL.

In app/controllers/foo/bar_controller.rb

before_action :verify_request_type  def my_action   case request.method_symbol   when :get     ...   when :post     ...   when :patch     ...   when :options     # Header will contain a comma-separated list of methods that are supported for the resource.     headers['Access-Control-Allow-Methods'] = allowed_methods.map { |sym| sym.to_s.upcase }.join(', ')     head :ok   end end  private  def verify_request_type   unless allowed_methods.include?(request.method_symbol)     head :method_not_allowed # 405   end end  def allowed_methods   %i(get post patch options) end 

In config/routes.rb

match '/foo/bar', to: 'foo/bar#my_action', via: :all 
like image 34
Dennis Avatar answered Oct 02 '22 10:10

Dennis