ruby-on-rails - ruby rails : Common method available for controllers and views?

标签 ruby-on-rails ruby authentication ruby-on-rails-4

我使用 Ruby on Rails 的时间很短。最近我为我的应用程序实现了一个身份验证系统。我在“application_helper.rb”上提供了一个方法来检索当前登录的用户(称为 current_user 的方法)。

如果 session[:user_id] 变量存在,该方法只检索我的 User 对象。

但是我遇到了以下问题。

  1. 如果我将 current_user 方法放在“application_helper.rb”中,我的 Controller 将无法使用它
  2. 如果我将 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/

相关文章:

ruby-on-rails - ActiveRecord 搜索分面计数

ruby-on-rails - Sidekiq 应该如何在作业完成时在网页上通知用户?

ruby-on-rails - 在 Ruby on Rails 中从 html 表单获取数据到 ruby

ruby-on-rails - Ruby on Rails - 设置评论功能

authentication - 是什么导致了此 Shibboleth 错误 : SAML 2 SSO profile is not configured for relying party?

azure - Passport-azure-ad 单点登录 (SSO)

security - Web API 身份验证和授权 (OAuth)

ruby-on-rails - 错误消息应与标签匹配

ruby-on-rails - 安装 nio4r 时出错

Ruby TCP 服务器 - 错误:PG::ConnectionBad:致命:剩余的连接槽保留用于非复制 super 用户连接