【问题标题】:How can I create a new object from a JSON POST?如何从 JSON POST 创建新对象?
【发布时间】:2013-06-22 00:30:25
【问题描述】:

我想使用 HTTP POST 从 json 在 Rails 服务器上创建一个新的“图像”对象。

这是 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 路线: $ 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

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

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

    【讨论】:

    • 很遗憾,仍然是“500 Internal Server Error”,模板丢失
    • 能贴一下图片相关的路线吗?通过运行 rake routes 来做到这一点。
    • 尝试将您的图像成功 json 更改为:format.json { render :json =&gt; @image }
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多