【发布时间】:2016-04-06 15:13:50
【问题描述】:
我在保存模型的序列化属性时遇到问题。我的课堂上有一个带有此功能的grape api。
# app/controllers/api/v1/vehicules.rb
module API
module V1
class Vehicules < Grape::API
include API::V1::Defaults
version 'v1'
format :json
helpers do
def vehicule_params
declared(params, include_missing: false)
end
end
resource :vehicules do
desc "Create a vehicule."
params do
requires :user_id, type: String, desc: "Vehicule user id."
requires :marque, type: String, desc: "Vehicule brand."
end
post do
#authenticate! @todo
Vehicule.create(vehicule_params)
end
我的模特是这样的
class Vehicule < ActiveRecord::Base
serialize :marque, JSON
当我在vehicule = Vehicule.create(user_id: 123, marque: {label: "RENAULT"} 这样的控制台中创建车辆时,它工作正常。
但是当我尝试发送请求时:curl http://localhost:3000/api/v1/vehicules -X POST -d '{"user_id": "123", "marque": {"label": "RENAULT"}}' -H "Content-Type: application/json" 我有这个错误消息:
Grape::Exceptions::ValidationErrors
marque is invalid, modele is invalid
grape (0.16.1) lib/grape/endpoint.rb:329:in `run_validators'
如果我用"marque": "{label: RENAULT}" 发送它,它可以工作,但它在数据库中保存为marque: "{label: RENAULT}",它应该是marque: {"label"=>"RENAULT"},因为我希望marque['label'] 返回RENAULT。
如何发送数据?
【问题讨论】:
标签: ruby-on-rails serialization grape