Grape API保存序列化属性

时间:2016-04-06 15:13:51

标签: ruby-on-rails serialization grape

我在保存模型的序列化属性时遇到问题。我班上有一个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"}的Vehicule时,它运行正常。

但是当我尝试发送请求时: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']返回{ {1}}。

我该如何发送数据?

1 个答案:

答案 0 :(得分:0)

我只需要在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