ruby - 如何通过在 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"
解决方案
您将'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
推荐阅读
- javascript - jquery加载函数不调用spring boot控制器来替换thymeleaf模板片段
- angular - 如何像我们在angular js中但在angular 5中一样包含html文件?
- javascript - 如何检查所有输入是否已正确填写,然后将其更改为绿色
- javascript - FullCalendar 尝试从 URL 而不是数组中获取事件
- javascript - Vuejs - 使用模板将父组件道具传递给子元素
- r - 在两个数据框中查找最接近的坐标匹配
- javascript - React - 加载外部脚本给我错误:无法在“文档”上执行“写入”
- postgresql - 如何授予用户对 Postgres 中所有新表的权限?
- java - 满足一定条件后自动在 JAVA swing 中配置框架
- vba - 粘贴的形状不被视为“最新”形状