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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With