2

我有一个 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 的正确请求)
POST
主机: http: //YADA.herokuapp.com/thanksgivings.json
内容类型:application/json 正文
:{"thanks":"qwerty"}

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

请求 3:(错误的键 - 将成功:值将为空,键将是“请求”作为响应,将添加数据库元素)
POST
主机:http: //YADA.herokuapp.com/requests.json
内容类型:应用程序/json 正文
:{"abc":"qwerty"}

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

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

4

1 回答 1

1

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

更改
@request = Request.new(params[:request])

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

于 2012-12-28T22:41:26.757 回答