我的会话控制器方法(对于API)使用模型方法生成令牌。接下来它应该使用json将令牌发送到前端。但是,在render json
行,api_token
已不再可用且为nil
。如何处理这个?
module Api
module V1
class ApiSessionsController < Api::BaseController
def create
user = User.friendly.find_by(email: create_params[:email].downcase)
if user && user.authenticate(create_params[:password])
user.create_api_token
render json: { api_token: api_token }, status: :ok
else
render json: {errors: "wrong credentials" }, status: :unauthorized
end
end
end
end
end
class User < ActiveRecord::Base
attr_accessor :api_token
has_secure_password
def create_api_token
begin
self.api_token = User.new_token
api_digest = User.digest(api_token)
end while self.class.exists?(api_digest: api_digest)
update_attributes(api_digest: api_digest, api_sent_at: Time.zone.now)
end
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end
答案 0 :(得分:1)
我相信该行应该看起来像
render json: { api_token: user.api_token }, status: :ok
您的控制器代码引用了api_token
变量,该变量未定义,因此您收到nil