ruby-on-rails – Rails:范围:为所有视图和控制器提供方法
发布时间:2020-12-17 01:52:31 所属栏目:百科 来源:网络整理
导读:几天我一直在努力争取范围.我希望所有视图和控制器都可以使用少量方法. 假设代码是: def login_role if current_user return current_user.role end return nilend 如果我将它包含在application_helper.rb中,那么它仅适用于所有视图,但不适用于所有控制器
几天我一直在努力争取范围.我希望所有视图和控制器都可以使用少量方法.
假设代码是: def login_role if current_user return current_user.role end return nil end 如果我将它包含在application_helper.rb中,那么它仅适用于所有视图,但不适用于所有控制器 如果我将它包含在application_controller.rb中,那么它可供所有控制器使用,但不适用于所有视图. 解决方法
在ApplicationController中使用
helper_method 方法为视图提供访问权限.
class ApplicationController < ActionController::Base helper_method :login_role def login_role current_user ? current_user.role : nil end end 考虑将所有相关的方法放在他们自己的模块中然后你可以使它们全部可用如下: 帮助者LoginMethods (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |