POST JSON数据到简单rails应用程序与curl [英] POST JSON data to simple rails application with curl

查看:159
本文介绍了POST JSON数据到简单rails应用程序与curl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个简单的新rails应用程序与模型条目,属性 title content 使用脚手架。

I set up a simple new rails application with model entry, with attributes title and content using scaffolding.

现在我试图使用curl来发布JSON数据(而不是使用浏览器)。

now I am trying to use curl to POST the JSON data (rather than using the browser).

以下似乎工作(即成功发布了空数据):

the following seems to work (i.e. successfully posted with null data):

curl --verbose --header "Accept: application/json" --header "Content-type: application/json" --request POST --data "" http://localhost:3000/entries

以下操作无效:

curl --verbose --header "Accept: application/json" --header "Content-type: application/json" --request POST --data "{'content':'I belong to AAA','title':'AAA'}" http://localhost:3000/entries

尝试了许多变化。

推荐答案

为了解决Jonathan说的问题, Post正在将数据发送到EntriesController。现在,在 create 操作中,您必须从 params 哈希中获取数据。我会假设你正在做这个有轨的方式,所以你会这样做:

To go along with what Jonathan said, the Post is now sending the data to the EntriesController. Now in your create action you have to get the data from the params hash. I am going to assume you are doing it the railsy way and so you would do something like this:

    curl -d 'entry[content]=I belong to AAA' -d entry[title]=AAA http://localhost:3000/entries'


b $ b

在您的控制器

In your controller

    Entry.create(params[:entry])

这说明从params哈希(由rails创建)抓取条目数据,并将其作为参数传递给Entry初始化一个新的对象。 create将在一个方法调用中为您执行新建和保存。

This says grab the "entry" data from the params hash (created by rails for you) and pass it as a parameter to Entry to initialize a new Object. "create" will do a "new" and "save" for you in one method call.

这篇关于POST JSON数据到简单rails应用程序与curl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆