2010-10-21 8 views
6

in Rails 2.3 Ho sempre usatoRails JSON iniezione

render :json => { :success => true, :data => @foobar} 

per inviare dati JSON al mio frontend. In Rails 3 sto usando

respond_to :json 
... 
respond_with @foobar 

Ma quello che mi manca: ho bisogno del valore di 'successo' all'interno della struttura JSON. Qual è il modo giusto per iniettare tali dati nella risposta JSON in Rails 3?


Hm, provato anche questo, ma ottengo il seguente errore come risultato:

SyntaxError (app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting '}' 
respond_with { :success => true, :data => @property } 
         ^
/app/controllers/properties_controller.rb:13: Can't assign to true 
respond_with { :success => true, :data => @property } 
           ^
app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.' 
respond_with { :success => true, :data => @property } 

risposta

1

Non è possibile utilizzare l'oggetto come valore. Basta aggiungere qualche chiave/valore all'interno con comando serializable_hash metodo

Ma si può generare la hash in respond_with

respond_with { :success => true, :data => @foobar} 
+0

Hmhm, provato anche questo, ma ottengo il seguente errore come risultato: – ctp

4

Quando le cose non si adatta il default, è necessario tornare al modo personalizzato precedente . respond_with accetta un blocco.

respond_with @foobar do |format| 
    format.json { render :json => { :success => true, :data => @foobar} } 
end