【问题标题】:Attributes is missing (grape API)缺少属性(葡萄 API)
【发布时间】:2015-10-07 09:10:55
【问题描述】:

我是 Rails 的新手。我尝试使用gem grape 编写一个小型 API Rails 应用程序。

我跟进了这个教程http://www.sitepoint.com/build-great-apis-grape/

但是当我尝试创建新记录时,出现错误: {"error":"type_id is missing"}

这是我的代码:

singers.rb

module V1
 class Singers < Grape::API
  resource :singers do
    desc "List all singers"
    get do
      Singer.all
    end

    desc "Create a new singer"
    params do
      requires :name, type: String
      requires :type_id, type: Integer
    end

    post do
      Singer.create!({
       name: params[:name],
       type_id: params[:type_id]
      })
    end
  end
 end
end

当我输入控制台时: curl http://localhost:3000/api/v1/singers.json -d "name=khanhpn;type_id=1"

我有一个错误:{"error":"type_id is missing"}

我不明白为什么它会抛出错误。希望大家能给我解释一下。非常感谢你。

这是我在 bitbucket 上推送的代码: https://bitbucket.org/baran19901990/grape_api/src/b8a0d676f17de3fedc95cc7efff60fab5afb0fc1/app/api/v1/singers.rb?at=master&fileviewer=file-view-default

解决方案:

curl -X POST http://localhost:3000/api/v1/singers -d "name=khanhpn&amp;type_id=1"

【问题讨论】:

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


    【解决方案1】:

    我认为问题不在于代码,而在于 curl 调用...

    尝试类似:

    curl -F name=khanhpn \
    -F type_id=1 \
    -X POST http://localhost:3000/api/v1/singers
    

    如果你想使用 -d 选项,或者使用单行命令,它会是这样的:

    curl -d "name=khanhpn" -d "type_id=1" -X POST http://localhost:3000/api/v1/singers
    

    【讨论】:

    • 我认为我们不需要在curl 中添加 POST。我们可以重写为:curl -X POST http://localhost:3000/api/v1/singers -d "name=khanhpn&amp;type_id=1" 我认为它更短。不过谢谢你的回答。
    【解决方案2】:

    问题在于将参​​数传递给curl。你必须用&amp;而不是;来分隔它们 curl http://localhost:3000/api/v1/singers.json -d "name=khanhpn&amp;type_id=1"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多