使用Postman的Ruby JSON API和发布请求

时间:2014-09-25 05:48:24

标签: ruby-on-rails ruby json api

我使用邮递员向我的rails / grape API发帖请求

这是json对象

{  
 "customer":{  
    "first_name":"Joe",
    "last_name":"Doe",
    "email":"test@test.com",
    "phone":"999-999-9999",
    "addresses_attributes":[{  
       "address":{  
          "address1":"123 somewhere st",
          "customer_id":"",
          "address2":"",
          "city":"Moldor",
          "state":"CA",
          "zip":"99999",
          "region_id":"1"
       }
    }]
 }
}

如果将其发送到api / v1 / customers.json 我收到以下错误消息

"error": "first_name is missing, last_name is missing, email is missing, phone is missing",

如果我将JSON格式更改为:

{   
    "first_name":"Joe",
    "last_name":"Doe",
    "email":"test@test.com",
    "phone":"999-999-9999",
    "addresses_attributes":[{  
       "address":{  
          "address1":"123 somewhere st",
          "customer_id":"",
          "address2":"",
          "city":"Moldor",
          "state":"CA",
          "zip":"99999",
          "region_id":"1"
       }
    }]
}

我确实创建了客户,但它没有创建地址

在我的模特中我有

#customer.br
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true

#address.rb
belongs_to :customer

这是api / vi / curtomer.rb

desc "Create a Customer"
params do
  requires :first_name, type: String, desc: "First Name"
  requires :last_name, type: String, desc: "Last Name"
  requires :email, type: String, desc: "Email"
  requires :phone, type: String, desc: "Phone"
  optional :notes, type: String, desc: "Notes"
end
post do


  # Tried with new instead of create

  # test = Customer.new({
  #                    first_name: params[:first_name],
  #                    last_name: params[:last_name],
  #                    email: params[:email],
  #                    phone: params[:phone],
  #                    notes: params[:notes],
  #                    addresses_attributes: params[:addresses]
  #                })


  Customer.create({
                     first_name: params[:first_name],
                     last_name: params[:last_name],
                     email: params[:email],
                     phone: params[:phone],
                     notes: params[:notes]
                     # addresses_attributes: params[:addresses]
                 })

end

地址看起来与客户几乎相同 我没有按照Grapes文档使用控制器

编辑:添加customer.rb创建代码

1 个答案:

答案 0 :(得分:1)

认为你的json数据应该是:

{ "customer":
  {   
    "first_name":"Joe",
    "last_name":"Doe",
    "email":"test@test.com",
    "phone":"999-999-9999",
    "addresses_attributes":[{    
      "address1":"123 somewhere st",
      "customer_id":"",
      "address2":"",
      "city":"Moldor",
      "state":"CA",
      "zip":"99999",
      "region_id":"1"
    }]
  }
}

请参阅this example

如果不起作用,请显示您的控制器代码。