【问题标题】:Grape API saving serialized attribute葡萄 API 保存序列化属性
【发布时间】: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"=&gt;"RENAULT"},因为我希望marque['label'] 返回RENAULT

如何发送数据?

【问题讨论】:

    标签: ruby-on-rails serialization grape


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多