【问题标题】:create a record for a current_user using postman ruby on rails在 rails 上使用 postman ruby​​ 为 current_user 创建记录
【发布时间】:2019-06-21 06:30:47
【问题描述】:

我确实有 2 个表用户和项目。当我尝试通过邮递员 API 创建项目时。我收到一个错误,即 items 为 nil,因为它正在寻找 current_user.items 并导致当我尝试创建项目时用户不是来自 API。

    @item = current_user.items.build(item_params)

当我尝试从邮递员创建项目时如何验证并成为 current_user 的问题?

这是我要发送的 API

 http://localhost:3000/api/v1/createitem

这是错误信息

    "exception": "#<NoMethodError: undefined method `items' for nil:NilClass>",

这里来自命令行

这个 items_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

错误发生在该行的 items_controller.rb 的第 81 行

    @item = current_user.items.build(item_params)

这是发送中的 json

{"item_category": "Books & Magazines", "item_condition": "Used", "item_name": "Crushing it", "summary": "super awesome", "price": 20, "active": true,"instant": 1}

这里是 application_controller.rb

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,它正在工作

http://localhost:3000/api/v1/login

【问题讨论】:

    标签: ruby-on-rails ruby postman rails-api


    【解决方案1】:

    首先你必须定义/获取current_user。由于 API 与 Web 应用程序完全不同,它们无法处理没有浏览器涉及的会话。所以我们需要以不同的方式处理授权。

    我假设您的登录 API 会为登录用户返回一些唯一令牌,如果不是您必须先实现它。

    您必须在标头中的每个 API 调用中传递该令牌并验证该令牌以获取 current_user

    Read this 获取更多参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多