2016-04-06 6 views
0

Ich habe ein Problem, serialisierte Attribut meines Modells zu speichern. Ich habe eine grape API mit dieser Funktion in meiner Klasse.Grape API Speichern serialisierten Attribut

# 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 

Mein Modell ist wie so

class Vehicule < ActiveRecord::Base 
    serialize :marque, JSON 

Wenn ich ein Fahrzeug in der Konsole wie vehicule = Vehicule.create(user_id: 123, marque: {label: "RENAULT"} schaffen es gut funktioniert.

Aber wenn ich versuche, eine Anfrage zu senden: curl http://localhost:3000/api/v1/vehicules -X POST -d '{"user_id": "123", "marque": {"label": "RENAULT"}}' -H "Content-Type: application/json" Ich habe diese Fehlermeldung:

Grape::Exceptions::ValidationErrors 
marque is invalid, modele is invalid 

grape (0.16.1) lib/grape/endpoint.rb:329:in `run_validators' 

Wenn ich es mit "marque": "{label: RENAULT}" sende es funktioniert, aber es ist in db als marque: "{label: RENAULT}" gespeichert und es sollte marque: {"label"=>"RENAULT"} sein, wie ich will marque['label'] zurückgeben RENAULT.

Wie kann ich die Daten senden?

Antwort

0

Ich musste einfach in der grape Controller den Typ des Attributs ändern.

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 

Und zu testen, können Sie so tun.

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 
Verwandte Themen