1

我是 Rails 的新手,很难将 cURL 发布到我的服务器。任何帮助将不胜感激。

我将 JSON 数据发布到我的服务器。这是我的卷曲帖子curl -X POST -H "Content-Type: application/json" -d '[{"photo":[{ "location": "location", "userID": "userid" },{ "location": "location", "userID": "userid" },{"location": "location", "userID": "userid"}]}]' http://localhost:3000/photo/create

这是我的控制器:

class SendphotoController < ApplicationController

    def create
    @photo = Photo.new(:photo => params[:location], :photo => params[:userID])
    respond_to do |format|
        if @photo.save
            puts "Done"
        else
            puts "NOPE"
        end 
    end     
end

我得到的错误ActionController::UnknownFormat (ActionController::UnknownFormat):

这是完整的日志:

Started POST "/photo/create" for 127.0.0.1 at 2013-09-08 22:03:56 -0400
Processing by SendphotoController#create as */*
  Parameters: {"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}], "sendphoto"=>{"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}]}}
WARNING: Can't mass-assign protected attributes for Photo: photo
    app/controllers/sendphoto_controller.rb:4:in `create'
   (0.0ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "photos" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00], ["updated_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00]]
   (215.8ms)  commit transaction
Done
Completed 406 Not Acceptable in 235ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/sendphoto_controller.rb:5:in `create'
4

1 回答 1

3

您使用的是respond_to块,但不是任何格式。您的块应如下所示:

respond_to do |format|
  format.html {
    # respond to a web form with HTML
  }

  format.json {
    # respond to API request
  }
end

如果您只想要所有格式的通用响应,则可以respond_to完全放弃该位。但是 puts不会在 Controller 上下文中工作(或者在 Rails 中的几乎任何地方);你必须render做点什么。

这可能看起来像这样

def create
  if Photo.create # ...
    render text: "done"
  else
    render text: "nope"
  end
end
于 2013-09-09T02:13:37.830 回答