我在rails 5 api中的会话控制器中一直收到此错误:
undefined method `[]' for nil:NilClass
老实说,我不确定自己做错了什么。这是我的会话控制器的代码(第8行发生错误):
module Api
class SessionsController < ApplicationController
def new
end
def create
# The error occurs on this line
@user = @User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
render :text => user.access_token, status: 200
else
render text: "Email and password combination are invalid", status: 422
end
end
def verify_access_token
user = User.find_by(access_token: params[:session][:access_token])
if user
render text: "verified", status: 200
else
render text: "Token failed verification", status: 422
end
end
end
end
这是我的sesssions帮助:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
# signed creates an encrypted cookie so that's why we use it.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns true if the given user is the current user.
def current_user?(user)
user == current_user
end
# Returns the current logged-in user (if any).
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Forgets a persistent session.
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# Redirects to stored location (or to the default).
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
# Stores the URL trying to be accessed.
def store_location
session[:forwarding_url] = request.url if request.get?
end
如果有人可以帮助我找到解决此错误的方法,我们将不胜感激。对于JSON api来说,我是一个新手。
答案 0 :(得分:0)
我投注参数[:session]为零。这就是为什么链接哈希键是一个坏主意。
另见Hash#dig https://ruby-doc.org/core-2.3.0/Hash.html#method-i-dig
(这对我来说是新闻!)
答案 1 :(得分:0)
@User
不是查找ActiveRecord对象的有效方法。它应该是模型的名称,大写,然后是查找方法。
将@user = @user...
更改为@user = User.find_by...
,您应该能够正确完成查找。
我喜欢做的一件事就是在有问题的线上方放置一个byebug,然后逐点构建查询&#39;在终端,看看我是否能找到我出错的地方。它还可以让你查看参数,以确保那里有东西。