I did some googling, but didn’t find anything that specifically
addressed my question, but if you have a link, I’d really appreciate it.
I want to build some robustness into my controllers by blocking access
to actions via the wrong request method. For example, I don’t want to
allow a POST to the :index action. I started using the verify method,
such as
verify :method => :get, :only => [:index, :new, :edit], :redirect_to =>
whatever
This worked well until I added some before_filters. It appears to me
that before_filters are processed before verify, and that is opposite
what I am trying to achieve. I’d like to check the request method before
anything else happens.
I came up with an approach in which I use a real before filter and a
hash of controllers, methods, and acceptable actions. It looks like
class ApplicationController < ActionController::Base
before_filter :verify_request_method
protected
def verify_request_method
if !request_method_valid?(controller_name.to_sym,
action_name.to_sym, request.method.to_sym)
flash[:error] = ‘Invalid request method.’
redirect_to error_path and return false
end
return true
end
private
def request_method_valid?(controller, action, method)
valid_request_methods = {
:welcome => {
:get => [:index, :about],
:post => [],
:put => [],
:delete => []
},
:users => {
:get => [:show, :new, :edit],
:post => [:create],
:put => [:update],
:delete => []
},
:sessions => {
:get => [],
:post => [:new],
:put => [],
:delete => [:destroy]
}
}
return valid_request_methods[controller][method].include?(action)
end
end
This works, but I’m curious if I’m making it more difficult than it
needs to be. Is there an easier way?
Peace,
Phillip