【问题标题】:Ruby on Rails: How to POST in my API?Ruby on Rails:如何在我的 API 中发布?
【发布时间】:2014-03-23 22:50:07
【问题描述】:

我正在尝试创建一个任务,但属性为空

小米控制器:

#app/controllers/api/v1/tasks_controller.rb
def create
   respond_with Task.create(params[:Task])
end

我尝试使用这些数据对 localhost:3000/api/v1/tasks 进行 POST:

{"task": {"name":"hello world"}}{"name":"hello world"}

但结果有属性为空:

#Response Body
{
   "id": 1,
   "name": null,
   "created_at": "2014-03-23T22:41:37.961Z",
   "updated_at": "2014-03-23T22:41:37.961Z"
}

更新:

# Server log
Started POST "/api/v1/tasks" for 127.0.0.1 at 2014-03-23 17:03:03 -0600
Processing by Api::V1::TasksController#create as JSON
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "tasks" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Sun, 23 Mar 2014 23:03:03 UTC +00:00], ["updated_at", Sun, 23 Mar 2014 23:03:03 UTC +00:00]]
   (153.5ms)  commit transaction
Completed 201 Created in 159ms (Views: 0.6ms | ActiveRecord: 154.0ms)

【问题讨论】:

  • 会不会是params[:Task] 中的大写符号,而不是params[:task]
  • 谢谢@vee。我改成小写了,但问题依旧
  • 服务器日志有没有线索?你检查过生成的插入查询吗? name 是否正确插入数据库?
  • 你能说明你是如何发布到这个网址的吗?调用 api/v1/tasks 后,你能在 Rails 日志中显示参数吗?
  • 你能调试代码并检查你是否在 params[:task] 上收到了一些东西吗?也许 params[:task] 或 params[:Task] 什么都不返回……而且 json 不会有问题……但是你的提交

标签: ruby-on-rails ruby json api http-post


【解决方案1】:

感谢 vee、emcanes、Carlos Figueiredo 和 BroiSatse 的回答。我解决了这个问题。

我更改了创建操作:

#app/controllers/api/v1/tasks_controller.rb
def create
   respond_with Task.create(task_params)
end

我补充说:

#app/controllers/api/v1/tasks_controller.rb
private
...
def task_params
  params.require(:task).permit(:name)
end

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多