Ruby-on-rails 从子类中的重载方法调用基类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1547074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling base class method from overloaded method in sub-class
提问by Jason Whitehorn
Perhaps I am just not using the correct terminology for Ruby (and if I am please correct me), but Google just isn't helping me on this one.
也许我只是没有使用正确的 Ruby 术语(如果我愿意请纠正我),但谷歌只是没有帮助我解决这个问题。
What I have is a class (call it OrderController) that extends another class (call it BaseStoreController). In the BaseStoreController I have defined a before_filterthat is used throughout my site, with the small except of my OrderController. In this very particular situation I needed to define a custom before_filterthat needs to do some additional logic and then call the before_filterdefined in my BaseStoreController.
我拥有的是一个类(称为 OrderController),它扩展了另一个类(称为 BaseStoreController)。在 BaseStoreController 中,我定义了一个before_filter在我的整个站点中使用的,除了我的 OrderController 之外的小。在这种非常特殊的情况下,我需要定义一个before_filter需要做一些额外逻辑的自定义,然后调用before_filter在我的 BaseStoreController 中定义的。
What I do not know is how to do this.
我不知道如何做到这一点。
Here is what I've tried, but it appears that the 'super' keyword isn't what I was expecting it to be:
这是我尝试过的,但似乎“超级”关键字不是我所期望的:
class BaseStoreController < ActionController::Base
before_filter :authorize
protected
def authorize
#common authroization logic here
end
end
and
和
class OrderController < BaseStoreController
before_filter :authorize
protected
def authorize
#additional authroization logic here
super.authorize
end
end
The end result of my code is that the authorize method in the OrderController is failing with the following error:
我的代码的最终结果是 OrderController 中的授权方法失败并出现以下错误:
You have a nil object when you didn't expect it! The error occurred while evaluating nil.authorize
回答by pythonquick
Have you tried calling the base class's "authorize" method with just "super" instead of "super.authorize"?
你有没有试过authorize只用“ super”而不是“ ”来调用基类的“ ”方法super.authorize?

