How to handle multiple HTTP methods in the same Rails controller action
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
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