【问题标题】:Can not create new user record on Rails api via Postman无法通过 Postman 在 Rails api 上创建新用户记录
【发布时间】:2016-09-15 13:25:09
【问题描述】:

我正在通过 Ruby on Rails 创建新的 api 应用程序。 所以我使用Devise 来管理我的用户表。

当我通过 Postman 发送请求来测试 api 时,它无法通过我的模型验证。

这是我的控制器

class UsersController < ApplicationController

  respond_to :json

  def create
    user = User.new(user_params)
    if user.save
      render json: user, status: 201, location: [:my, user]
    else
      render json: { errors: user.errors }, status: 422
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation,:username,:fullname,:grade)
  end

end

这是我通过 Postman 发送到服务器的数据

{
    "user"  : {
        "email": "test5@gmail.com",
        "password": "123456",
        "password_confirmation": "123456",
        "username": "yofoyf",
        "fullname": "narotuo sarp",
        "grade": "aaa"
    }
}

而且我也将标头设置为 application/json 像这样

但是当我点击发送时出现错误,因为它无法像这样通过我的验证

Sign up

3 errors prohibited this user from being saved:

Username can't be blank
Grade can't be blank
Fullname can't be blank

这是我的模特

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :username, presence: true ,uniqueness: true
  validates :grade, presence: true
  validates :fullname, presence: true

end

那么我怎样才能让邮递员工作呢? 服务器似乎无法读取我的用户名、全名和成绩记录。

谢谢!

【问题讨论】:

  • 您是否尝试将用户作为外层 JSON 对象发送?
  • 在 postman 的 body 部分设置参数,比如这个 user[:email] 值
  • @AdamRosini 你有什么例子吗?
  • @Navin 你的意思是每条记录一个一个地设置?
  • 是的,您已经在邮递员的正文部分将参数一一发送,例如 user[:email] 值,然后在下一行 user[:password] 123456 中为每条记录发送并点击发送按钮。

标签: ruby-on-rails json devise postman


【解决方案1】:

尝试像这样发布您的用户:

{
    "email": "test5@gmail.com",
    "password": "123456",
    "password_confirmation": "123456",
    "username": "yofoyf",
    "fullname": "narotuo sarp",
    "grade": "aaa"
}

【讨论】:

  • 不工作似乎需要:用户获得通行证。
【解决方案2】:

你已经把参数一一发送到邮递员的正文部分,如下所示

user[:email] "test5@gmail.com"  // then in next line 
user[:password] 123456

对于每条记录,您必须通过新请求传递参数并点击发送按钮

【讨论】:

  • 我像您所做的那样通过表单数据将数据传递给正文,但它仍然无法正常工作。我得到了ActionDispatch::ParamsParser::ParseError
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多