首页 > 解决方案 > 如何通过在 rails 5 restful json api 中传递用户 authentication_token 来显示用户对象数据?

问题描述

在 v1/控制器中

类 V1::ProfilesController < ApplicationController

def index

 if user = User.authentication_keys.present?

    user = User.all

    render json: {status: 'load', message:'load', user: 'user'},status: :ok

    else

    render json: {status: 'error', message:'error', user: 'user'},status: :ok

    end
  end

在路线中

namespace :v1 do
resources :profiles
end

我通过传递 authentication_token 检查邮递员中的数据,但它不显示用户对象邮递员图像] 1

我在 Rails 控制台中的用户数据

用户ID:1,电子邮件:“adarsh1454@codekyt.com”,created_at:“2018-11-14 07:35:59”,updated_at:“2018-11-14 07:35:59”,authentication_token:“tYHzjLm- 6xxCeM4RXyEe"

标签: rubyruby-on-rails-5

解决方案


您将'user'作为字符串传递给您的 json。所以它只会发送那个字符串。您可以尝试执行以下操作:

render json: {status: 'load', message:'load', user: user.to_json},status: :ok

甚至:

render json: user

这将摆脱状态和消息 json 属性,但您可能会争辩说状态应该由 HTTP 响应代码显示,并且如果您将用户作为响应传递,则不需要该消息。

编辑

好的,根据您的评论,我认为您可能需要以下内容:

def index
  if request.headers["authentication_token"].present?
    user = User.find_by(authentication_token: request.headers["authentication_token"])     
    render json: user
  else
    render json: { .... whatever you want to render if not authorised }
  end
end

推荐阅读