我们如何重写 Rails 中的 ActionController 来共用某些方法?
我有可在多个控制器上使用的身份验证代码。所以我想到将身份验证代码放入一个超类中,然后让所有其他控制器扩展这个超类。然后我知道我们可以将它添加到 ActionController 类本身中。我们怎样才能做到这一点?有没有办法改变预定义的类?
I have the authentication code to be available over several Controllers. So I thought of putting the Authentication code in to a SuperClass and then make all the other controllers extend this SuperClass. I then got to know that we can add it in the ActionController class itself. How can we do that? Is there a way to change the pre defined class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将方法添加到位于 app/controllers/application_controller.rb 中的 ApplicationController 类,并且它是所有项目控制器的直接超类(假设您使用 script/generate 创建了控制器并且没有更改超类)。
You should add the methods to the ApplicationController class which lives in app/controllers/application_controller.rb and is the direct superclass of all your project's controllers (assuming you created your controllers with script/generate and did not change the superclass).
实际上,您的所有控制器都应该已经继承自
ApplicationController
,而 ApplicationController 又继承自ActionController::Base
。将身份验证代码包含到ApplicationController
中确实是非常惯用的。Actually all your controllers should already inherit from
ApplicationController
, which in turn inherits fromActionController::Base
. And including authentication code intoApplicationController
is quite idiomatic, really.所有控制器都已扩展
ApplicationController
,因此只需在ApplicationController
中添加一个授权方法和一个调用该方法的before_filter
即可你所有的控制器。All controllers already extend
ApplicationController
, so simply add an authorize method and abefore_filter
calling that method in yourApplicationController
and you'll be all set for all your controllers.