How do you append a filter to the very end of a filter chain from a superclass?

倖福魔咒の 提交于 2019-12-08 05:36:15

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/1146987/how-do-you-append-a-filter-to-the-very-end-of-a-filter-chain-from-a-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!