我想定义一个after_filter
来恢复before_filter
的更改,这样所做的更改只会影响我控制器中的一个操作。这是我到目前为止所做的:
before_filter :exclude_root_in_json
after_filter :restore_root_in_json
def exclude_root_in_json
ActiveRecord::Base.include_root_in_json = false
end
def resotre_root_in_json
ActiveRecord::Base.include_root_in_json = true
end
我有什么方法可以做以下的事情吗?
def exclude_root_in_json
default = ActiveRecord::Base.include_root_in_json
ActiveRecord::Base.include_root_in_json = false
self.class.after_filter do
ActiveRecord::Base.include_root_in_json = default
end
end
我的最终结果是以before_filter
调用结束,该调用会在该操作完成后自动撤消该特定操作的更改。我该怎么做?
答案 0 :(得分:1)
听起来您可以使用around_filter
。查看api文档的此页面:
http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
尝试如下:
around_filter :exclude_root_in_json
private
def exclude_root_in_json
default = ActiveRecord::Base.include_root_in_json
ActiveRecord::Base.include_root_in_json = false
yield
ActiveRecord::Base.include_root_in_json = default
end