POST JSON data to simple rails application with curl

前端 未结 3 908
臣服心动
臣服心动 2021-02-02 02:04

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

now I am trying to use curl to

相关标签:
3条回答
  • 2021-02-02 02:42

    I ran a test and got the error MultiJson::DecodeError (743: unexpected token at '{'content':'I belong to AAA','title':'AAA'}'):

    JSON requires double quotes for keys and strings, not single quotes. Try --data '{"content":"I belong to AAA","title":"AAA"}'

    0 讨论(0)
  • 2021-02-02 02:51

    take a block of JSON

    {\"a\":\"this_is_a\"}
    

    and url encode it

    %7B%22a%22%3A%22this_is_a%22
    

    and then use curl to post it

    curl -i --data "working_params=%7B%22a%22%3A%22this_is_a%22" http://url/accepts/json
    
    0 讨论(0)
  • 2021-02-02 02:59

    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'
    

    In your controller

        Entry.create(params[:entry])
    

    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.

    0 讨论(0)
提交回复
热议问题