2013-06-21 218 views
0

我想使用HTTP POST从json在Rails服务器上创建一个新的“Image”对象。如何从JSON POST创建新对象?

这里的images_controller代码:

class ImagesController < ApplicationController 
    respond_to :json 

    def create 
    @image = Image.new(params[:image]) 

    respond_to do |format| 
     if @image.save 
     format.html { redirect_to images_path } 
     format.json { render :success => true } 
     else 
     format.html { render "new" } 
     format.json { render json: @image.errors, status: :unprocessable_entity } 
     end 
    end #respond_to 
    end 
end 

的routes.rb:

MyServer::Application.routes.draw do 

    post 'images' => 'images#create' 

end 

我使用的是Chrome浏览器扩展 “简单的REST客户端”。 这个请求:

URL: http://localhost:3000/images 
METHOD: POST 
Headers: 
Content-Type: application/json 
Accept: application/json 

Data: 
{"image": { "title":"myImage", "url": "someUrl" } } 

这是响应:

Status:500 Internal Server Error 
Data: 
<title>Action Controller: Exception caught</title> 
     <h1>Template is missing</h1> 
    <p>Missing template images/create, application/create with {:locale=&gt;[:en], :formats=&gt;[:json], :handlers=&gt;[:erb, :builder, :coffee]}. Searched in: 
     * &quot;c:/Users/XXX/workspaceRubyOnRails/my_server/app/views&quot; 
    </p> 

运行rake路线: $耙路线

images_edit GET /images/edit(.:format) images#edit 
images_new GET /images/new(.:format) images#new 
    images GET /images(.:format)  images#index 
     image GET /images/:id(.:format) images#show 
    images POST /images(.:format)  images#create 

回答

1

尝试将请求发送到http://localhost:3000/images.json而不是http://localhost:3000/images

+0

不幸的是,仍然出现“500内部服务器错误”,模板丢失 –

+0

您可以粘贴与图像相关的路线吗?通过运行'rake routes'来做到这一点。 – darksky

+0

images POST /images(.:format)images#create –