How do you append a filter to the very end of a fi

2019-06-02 08:11发布

in rails when you register filters in abstract superclasses they come before the filters registered in the controller class. Say I wanted to execute a method called authenticate as a filter right at the end of the filter chain. The only way I can figure it out is to declare that before_filter as the last filter in all my controller classes (and there are many of them). Is there a way to declare this filter in the superclass and have it still be executed last? The reason I want it executed last is that the controller class might modify the authentication requirements just for that controller, and I want these modifications to be taken into account before the final authentication filter is called.

2条回答
叼着烟拽天下
2楼-- · 2019-06-02 08:23

Use prepend_before_filter in your controller classes instead of before_filter or append_before_filter.

查看更多
混吃等死
3楼-- · 2019-06-02 08:26

Rails calls your ApplicationController first, before the local one... so you can do something like this (using your example):

In your Application controller you'll have your before_filter callback, and a corresponding method that gets called:

before_filter :authenticate


def authenticate
  # do something
end

In the controller for the resource type you're working with...

You can redefine / override authenticate

def authenticate
 # do something else
end

You can even choose NOT to use your authenticate callback for some methods

skip_before_filter :authenticate, :only => :my_method_without_auth
查看更多
登录 后发表回答