葡萄 API 保存序列化属性

Grape API saving serialized attribute

我在保存模型的序列化属性时遇到问题。我的 class.

中有一个具有此功能的 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'] 到 return RENAULT.

如何发送数据?

我只需要在 grape 控制器中更改属性的类型。

desc "Create a vehicule."
  params do
    requires :user_id, type: Integer, desc: "Vehicule user id."
    requires :marque, type: Hash, desc: "Vehicule brand."
  end
  post do
    #authenticate! @todo
    Vehicule.create(vehicule_params)
  end

为了测试,你可以这样做。

test "PUT /api/v1/vehicules/1" do
  put("/api/v1/vehicules/1", {"id" => 1,"user_id" => 1,"marque" => {"label" => "RENAULT"}}, :format => "json")
  assert(200, last_response.status)
  vehicule = Vehicule.find(1)
  assert_equal("RENAULT", vehicule.marque['label'], "La marque devrait être")
end