【问题标题】:Rails 3 error in Safari only - ActiveRecord::RecordNotFound (Couldn't find User with auth_token = ):仅在 Safari 中出现 Rails 3 错误 - ActiveRecord::RecordNotFound(找不到具有 auth_token = 的用户):
【发布时间】:2012-02-28 13:56:25
【问题描述】:

在遵循 Railscast #274 以在我的 Rails 3 应用程序中重置密码时,我在 Safari 中遇到了一个奇怪的问题。如果我在 Heroku 中运行我的应用程序,当我转到我的根目录时会收到以下错误:

ActiveRecord::RecordNotFound (Couldn't find User with auth_token = ):
app/controllers/application_controller.rb:39:in `lookup_user'
app/controllers/application_controller.rb:32:in `current_user'
app/controllers/application_controller.rb:54:in `logged_in?'
app/controllers/users_controller.rb:8:in `new'

如果使用 Firefox 和 Chrome(在隐身模式下),它可以工作。在 Safari 中,我发现如果出现错误,我可以通过导航到 /logout 使其消失。然后页面完美呈现。

这是我前往/logoutroot 的路线:

match "/logout" => "sessions#destroy", :as => "logout"
root :to => "users#new"

这是我在sessions_controller 中的destroy 操作:

def destroy
  reset_session
  cookies.delete(:auth_token)
  redirect_to root_path, :notice => "You successfully logged out"
end

我的application_controller

protected

  def current_user
    @current_user ||= lookup_user
  end

  def lookup_user
    if session[:user_id]
      User.find_by_id(session[:user_id])
    elsif cookies[:auth_token]
      User.find_by_auth_token!(cookies[:auth_token])
    end
  end

最后,这是我在users_controller 中的new 操作:

定义新 @user = User.new @user.profile = Profile.new 如果已登录? 重定向到配置文件路径(当前用户) 结尾 结束

我的尝试:

要更改 new 操作以删除 cookie,请使用以下内容:

def new
  @user = User.new
  @user.profile = Profile.new
  if logged_in?
    redirect_to profile_path(current_user)
  elsif
    cookies.delete(:auth_token)
  end
end

下面的 rake 任务,如 Railscast comments 中所建议的:

namespace :user do
  desc "Rebuild Auth-Tokens"
  task :rebuild_auth_token => :environment do
    User.transaction do
      User.all.each { |u|
        u.generate_token(:auth_token)
        u.save!
      }
    end
  end
end

(I ran this with `heroku run rake user:rebuild_auth_token`)

似乎都没有奏效。谁能帮我解决这个问题?

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    每当您重新生成用户 :auth_code's 时,您都需要删除该域的 cookie。在生产中,您不应该重新生成 :auth_codes 并且您永远不会遇到这个问题,除非用户编辑他们的 cookie。

    此外,我还发布了有关 railscast.com 身份验证(修订)解决方案的回复,以便 Ryan 可以查看。

    祝你好运!

    【讨论】:

    • 感谢您的回复。我将您的代码添加到我的 lookup 方法中,它似乎使我的应用程序崩溃。我尝试使用/不使用return nil,并剥离了除cookies.delete(:auth_token) 之外的所有内容,但这与我遇到的错误相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2017-03-18
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多