我使用 Ruby on Rails 的时间很短。最近我为我的应用程序实现了一个身份验证系统。我在“application_helper.rb”上提供了一个方法来检索当前登录的用户(称为 current_user 的方法)。
如果 session[:user_id]
变量存在,该方法只检索我的 User
对象。
但是我遇到了以下问题。
- 如果我将
current_user
方法放在“application_helper.rb”中,我的 Controller 将无法使用它 - 如果我将
current_user
方法放在“application_controller.rb”中,我的 View 将无法使用它
解决此问题的最佳方法是什么?简单的方法是在 Controller 和助手中复制我的代码,但我知道有更好、更正确的方法。
提前致谢
最佳答案
这是一个常见且已得到很好解决的问题。
Rails 不允许 Controller 访问辅助方法。如果你想在你的 View 和 Controller 之间共享一个方法,你需要在你的 Controller 中定义这个方法,然后用 helper_method
让它对你的 View 可用。 :
class ApplicationController < ActionController::Bbase
# Let views access current_user
helper_method :current_user
def current_user
# ...
end
end
您可以将多个方法名称传递给 helper_method
以使 Controller 中的其他方法可用于您的 View :
helper_method :current_user, :logged_in?
def current_user
# ...
end
def logged_in?
!current_user.nil?
end
关于ruby-on-rails - ruby rails : Common method available for controllers and views?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24088650/