2016-04-06 3 views
0

モデルのシリアル化された属性を保存する際に問題が発生しました。私はgrape私のクラスでこの機能を持つAPIを持っています。私はそれが正常に動作しますvehicule = Vehicule.create(user_id: 123, marque: {label: "RENAULT"}のようなコンソールでVEHICULEを作成するとブドウ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 

のようなものです。

しかし、私は、要求送信しようとすると: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}"としてDBに保存されますと、私が好きな、それはmarque: {"label"=>"RENAULT"}する必要がありますからRENAULTを返す。

どのようにデータを送信できますか?

答えて

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 
関連する問題