0

我正在尝试创建一个简单的 crud 接口来吐出一些 json。(API)

我正在使用鼓舞人心的狂欢代码库来制作它,到目前为止,还没有任何令牌可以确保它的安全

请看下面的代码:

助手/api/api_helper.rb

module Api
  module ApiHelper
    def required_fields_for(model)
      required_fields = model._validators.select do |field, validations|
        validations.any? { |v| v.is_a?(ActiveModel::Validations::PresenceValidator) }
      end.map(&:first)
    end

    def product_attributes
      [:id, :name]
    end
  end
end

意见/api/products/new.rabl

object false
node(:attributes) { [*product_attributes] }
node(:required_attributes) { required_fields_for(Product) }

控制器/api/products_controller.rb

def new
end

def create
  @product = Product.new(params[:product])
  if @product.save
    respond_with(@product, :status => 201, :default_template => :show)
  else
    invalid_resource!(@product)
  end
end

当我通过 curl 进行发布请求时,由于产品名称不应为空(模型验证),该方法返回 422 Unprocessable Entity 错误。如您所见,名称设置正确!

没发现这有什么问题(序列化?)谢谢你的想法

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"attributes":{"name":"test"}}'  http://localhost/api/brands

* About to connect() to localhost port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> POST /api/products HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost
> Accept: application/json
> Content-type: application/json
> Content-Length: 31
> 
< HTTP/1.1 422 Unprocessable Entity
< Content-Type: application/json; charset=utf-8
< X-Meta-Request-Version: 0.2.0
< X-UA-Compatible: IE=Edge
< Cache-Control: no-cache
< X-Request-Id: e32527947ed4ae51052b4d65d9d4539f
< X-Runtime: 0.042655
< Connection: close
< 
* Closing connection #0
{"errors":{"name":["doit \u00eatre rempli(e)"]}}
4

1 回答 1

0

JSON 有效负载应该嵌套在模型的名称下。尝试这个:

-d ' {"product":{"name":"test"}}'
于 2013-01-15T09:40:41.197 回答