我目前正在使用rails api开发API,我对多个设计用户模型存在一些问题。我也在使用simple_token_authentication gem有助于生成用于身份验证的令牌。
所以目前我已经为设计创建了这个2用户模型。 用户和 的管理
我对这个2设计模型的控制器是非常相同的,这是我的用户和管理设备的数据库属性,基本上我的destroy方法将从我的数据库重置我的token_authentication。
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "authentication_token"]
这是数据库
中的管理员帐户示例条目=> <Admin id: 1, email: "admin@gmail.com", created_at: "2017-07-19 15:05:49", updated_at: "2017-07-19 15:05:49", authentication_token: "UAUK6JngFVbRr5QYeeFo">
现在我的问题是,我的管理控制器上的DELETE #destroy方法一直出现错误,但我的用户控制器销毁方法工作正常。
{"status":500,"error":"Internal Server Error","exception":"#\u003cNoMethodError: undefined method `save' for nil:NilClass\u003e","traces":{"Application Trace":[{"id":0,"trace":"app/controllers/v1/adminsessions_controller.rb:20:in `destroy'"}],"Framework Trace":[{"id":1,"trace":"actionpack (5.1.2) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'"},{"id":2,"trace":"actionpack (5.1.2) lib/abstract_controller/base.rb:186:in `process_action'"},
以下是我的控制器的样子
管理员会话控制器
class V1::AdminsessionsController < ApplicationController
def show
current_admin ? head(:ok) : head(:unauthorized)
end
def create
@admin = Admin.where(email: params[:email]).first
if @admin&.valid_password?(params[:password])
render :create, status: :created
else
render json: {
message: "Wrong password or email"
}.to_json, status: :unauthorized
end
end
def destroy
current_admin&.authentication_token = nil
if current_admin.save
head(:ok)
else
head(:unauthorized)
end
end
end
用户会话控制器
class V1::SessionsController < ApplicationController
def show
current_user ? head(:ok) : head(:unauthorized)
end
def create
@user = User.where(email: params[:email]).first
if @user&.valid_password?(params[:password])
render :create, status: :created
else
render json: {
message: "Wrong password or email"
}.to_json, status: :unauthorized
end
end
def destroy
current_user&.authentication_token = nil
if current_user.save
head(:ok)
else
head(:unauthorized)
end
end
end
它一直在说未定义的方法`save&#39;所以我去了bybbug,我发现current_admin是零,我无法弄清楚为什么它总是为零。我已经在标题中传递了令牌和电子邮件。请帮帮我们谢谢!