【问题标题】:Posting json requests to Ruby on Rails server app – 500 error向 Ruby on Rails 服务器应用程序发布 json 请求 - 500 错误
【发布时间】:2012-12-28 00:43:56
【问题描述】:

我有一个 Ruby on Rails 服务器应用程序(托管在 Heroku 上),它应该能够接收带有 JSON 字符串的 HTTP POST 请求并将 JSON 对象添加到数据库中。有两种数据库模型:感恩节和请求。

控制器/request_controller.rb:

class RequestsController < ApplicationController
  [...]
  # POST /requests
  # POST /requests.json
  def create
    @request = Request.new(params[:request])

    respond_to do |format|
      if @request.save
        format.html { redirect_to @request, notice: 'Request was successfully created.' }
        format.json { render json: @request, status: :created, location: @request }
      else
        format.html { render action: "new" }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end
[...]
end

对于感恩节数据库模型和请求数据库模型,不同数据库模型对象值的 JSON 键应分别为“thanks”和“request”。

模型/request.rb:

class Request < ActiveRecord::Base
  attr_accessible :request
end

模特/感恩节.rb:

class Thanksgiving < ActiveRecord::Base
  attr_accessible :thanks
end

当我向 http://YADA.herokuapp.com/thanksgivings.json 发布 HTTP 请求时,一切正常,但是当我将其发送到 .../requests.json 时,我收到 500 错误。如果我在 JSON 字符串中使用了错误的键,则请求成功,但值变为空。

请求 1:(对 Thanksgiving.json 的正确请求)
发布
主持人:http://YADA.herokuapp.com/thanksgivings.json
内容类型:application/json
正文:{"thanks":"qwerty"}

请求 2:(对 request.json 的正确请求 - 返回 500)
发布
主持人:http://YADA.herokuapp.com/requests.json
内容类型:application/json
正文:{"request":"qwerty"}

请求 3:(错误键 - 将成功:值将为空,响应中的键将为“请求”,将添加数据库元素)
发布
主持人:http://YADA.herokuapp.com/requests.json
内容类型:application/json
正文:{"abc":"qwerty"}

奇怪的是,thanksgivings_controller.rb 和 requests_controller.rb 这两个控制器是“相同的”,但它们的行为却不同。

任何人都知道如何成功地做到这一点?

【问题讨论】:

  • 从这些请求中发布服务器日志——我敢打赌,只要看看它们就会让您很好地了解为什么会发生这种情况。

标签: ruby-on-rails json httprequest


【解决方案1】:

根据服务器日志,有一个 NoMethodError – stringify_keys。这个问题的答案就是解决方案:undefined method `stringify_keys'

变化
@request = Request.new(params[:request])

@request = Request.new(:request =&gt; params[:request])
成功了。

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 2012-06-06
    • 1970-01-01
    • 2019-09-11
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多