我正在尝试创建一个简单的crud接口,吐出一些json。(api)
我正在使用鼓舞人心的spree代码库,以使它,到目前为止,没有令牌使其安全
请参阅下面的代码:
辅助/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/产品/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做post请求时,该方法返回一个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)"]}}
JSON有效负载预计嵌套在模型的名称下。试试这个:
-d ' {"product":{"name":"test"}}'