【问题标题】:Rails + Authlogic @current_user problem - "Show" method no longer worksRails + Authlogic @current_user 问题 - “显示”方法不再有效
【发布时间】:2011-01-21 21:32:44
【问题描述】:

我在我的 rails 应用程序中实现了 Authlogic,该应用程序运行良好且测试良好。用户可以登录、注销等。

但是,由于我将 users_controller 中的方法更改为使用 @current_user 变量,所以我的任何用户方法或表单都没有(奇怪的是“索引”除外.. .) 工作!

例如,这个“显示”方法可以工作并显示任何用户的用户配置文件(注意:我想最终以某种方式将其限制为当前登录的用户):

def show
    @user = User.find(params[:id])
end

如果我按照 Authlogic rails cast 和官方示例中所示的 show 方法:

def show
    @user = @current_user
end

我收到各种undefined method METHOD for nil:NilClass 错误。似乎 @current_user 变量不包含任何用户信息。

我假设@current_user 正在从 current_user 方法中提取信息,如下面的应用程序控制器中所定义:

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

我错过了什么?我的直觉是用户模型中的用户对象和 current_user 方法之间没有映射。任何帮助将不胜感激!

提前致谢!

~丹

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 authlogic


    【解决方案1】:

    不应该只是

    def show
        @user = current_user
    end
    

    没有@?

    【讨论】:

    • 正确,Devise 为您提供了current_user 方法。
    • 知道我调用的是方法而不是预定义的变量对我来说很有意义。这有点令人困惑,因为网上的大部分示例代码都将其设置为 @user = @current_user。再次感谢您的帮助!这就是我喜欢 StackOverflow 的原因
    【解决方案2】:

    current_user 是 authlogic 自带的 helper,所以你必须在没有'@'的情况下使用它。 通常你创建@sothing 将它从控制器传递到视图,所以你将访问你在action方法中准备的东西。

    【讨论】:

    • 有道理...我想知道他们为什么在 Github 上的示例代码中这样设置?
    【解决方案3】:

    我在使用 authlogic 和 rails 3 时遇到了类似的问题,这是因为我在生产服务器上使用了 apache http 身份验证。 我通过将以下行添加到我的 user_session.rb(model) 来解决这个问题

        allow_http_basic_auth false
    

    这是救了我一命的博客链接http://www.christopherirish.com/2011/08/12/rails-3-authlogic-sessions-not-persisting-in-production/comment-page-1/#comment-181

    【讨论】:

    • 究竟是什么问题?你能澄清一下吗? `allow_http_basic_auth false' 有什么作用?
    【解决方案4】:
    def
    if @current_user
     @user = @current_user
    else
     @user = User.find(params[:id])
    end
    end
    

    只是猜测,试一试。

    【讨论】:

    • 这不是完整的答案,但我最终使用这个想法让未登录的用户查看个人资料。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多