问题描述
更多新手问题.
我明白,如果我在我的应用助手中定义了一个方法,它对整个应用代码都是可用的.
I understand that if I define a method in my application helper, it is available to the entire app code.
在我的应用程序助手中,我有:
In my applicaton helper, I have:
def primary_user_is_admin
if current_user
user_login_roles = JSON.parse(current_user.role)
if user_login_roles["admin"]
return 1
end
end
return nil
end
如果我从 category_controller 调用它:
If I call it from the categories_controller:
if !primary_user_is_admin
redirect_to root_url
end
我收到一条错误消息:未定义的局部变量或方法`primary_user_is_admin'
I get an error message: undefined local variable or method `primary_user_is_admin'
如果我将 primary_user_is_admin 代码放在 registrations_helper.rb 文件中,也会发生这种情况
This also happens if I put the primary_user_is_admin code in the registrations_helper.rb file
但是,如果我在任何视图中使用它(例如views/user/edit.html.erb)
However, if I use it in any of the views (views/user/edit.html.erb for instance)
<% if primary_user_is_admin %>
<% end >
然后就可以了.我错过了什么?
then it works. What am I missing?
推荐答案
默认情况下,帮助程序不包含在控制器中.你可以
Helpers are not included into a controller by default. You can
include ApplicationHelper
访问 ApplicationHelper 模块中的方法.之前的讨论有很多有用的解决方案来访问控制器中的助手.
To gain access to the methods in the ApplicationHelper module. The previous discussion has a bunch of useful solutions for accessing helpers in controller.
这篇关于Rails:在 application_helper.rb 中定义的方法不被 category_controller.rb 识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!