Ruby on rails 使用postman ruby on rails为当前用户创建记录
我有2个表用户和项目。当我尝试通过postman API创建项目时。我得到一个错误,items为nil,因为它正在查找当前的_user.items,并且在我尝试创建项时,导致用户不是来自APIRuby on rails 使用postman ruby on rails为当前用户创建记录,ruby-on-rails,ruby,postman,rails-api,Ruby On Rails,Ruby,Postman,Rails Api,我有2个表用户和项目。当我尝试通过postman API创建项目时。我得到一个错误,items为nil,因为它正在查找当前的_user.items,并且在我尝试创建项时,导致用户不是来自API @item = current_user.items.build(item_params) 当我尝试从postman创建项目时,如何进行身份验证并成为当前用户 这是我正在发送的API http://localhost:3000/api/v1/createitem 下面是错误消息 "e
@item = current_user.items.build(item_params)
当我尝试从postman创建项目时,如何进行身份验证并成为当前用户
这是我正在发送的API
http://localhost:3000/api/v1/createitem
下面是错误消息
"exception": "#<NoMethodError: undefined method `items' for nil:NilClass>",
这是发送中的json
{"item_category": "Books & Magazines", "item_condition": "Used", "item_name": "Crushing it", "summary": "super awesome", "price": 20, "active": true,"instant": 1}
这是应用程序_controller.rb
class Api::V1::ItemsController < ApplicationController
def createitem
@item = current_user.items.build(item_params)
if @item.save
redirect_to listing_item_path(@item), notice: "Saved..."
else
flash[:alert] = "Something went wrong..."
render :new
end
end
def item_params
params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant)
end
end
class ApplicationController < ActionController::API
include Authenticate
rescue_from ActiveRecord::RecordNotFound, with: :render_404
def render_404
render json: { error: "Invalid ID", is_success: false}, status: 404
end
end
首先,您必须定义/获取
当前用户
。由于API和web应用程序完全不同,它们无法处理会话,因为不涉及浏览器。因此,我们需要以不同的方式处理授权
我假设您的登录API为登录的用户返回一些唯一的令牌,如果不是,那么您必须首先实现它
您必须在标头中的每个API调用中传递该令牌,并验证该令牌以获取当前用户
请提供更多参考
class ApplicationController < ActionController::API
include Authenticate
rescue_from ActiveRecord::RecordNotFound, with: :render_404
def render_404
render json: { error: "Invalid ID", is_success: false}, status: 404
end
end
http://localhost:3000/api/v1/login