2010-12-16 14 views
6

tengo un método post llamado combinación que debe hacer lo siguiente: 1) crear un nuevo objeto 2) responder con un objeto JSONrespon_with no funciona en ruby ​​on rails. ¿Por qué?

Aquí está mi código:

class GameController < ApplicationController 

    respond_to :json 

    def join 
    @p = Player.new(:name => params[:name]) 
    @p.save! 
    respond_with({:uuid => @p.uuid}) 
    end 
end 

Por alguna razón, la llamada respond_with siempre produce este error:

undefined method `model_name' for NilClass:Class 

Si cambio la llamada respond_with a algo más simple sigo teniendo errores, por ejemplo:

respond_with "hello" 

produce este error:

undefined method `hello_url' for #<GameController:0x1035a6730> 

¿Qué estoy haciendo mal ?? ¡Solo quiero devolverles un objeto JSON!

PS, mi archivo de rutas es el siguiente:

match 'join' => 'game#join', :via => :post 
+1

Es mejor que ditching 'respond_with' y simplemente usando el viejo y simple 'format.json {render: json}' etc. si desea apartarse de las acciones del controlador estándar. – zetetic

+0

Eso es exactamente lo que terminé haciendo :-) –

Respuesta

7

Creo que los métodos respond_with requiere que usted pase el recurso (@p) como argumento. Aquí está some documentation for the method.

Prueba esto:

respond_with @p, :only => [:uuid] 

También podría representar JSON como esto:

render :json => { :uuid => @p.uuid } 
+2

De hecho terminé usando render: json, esto funcionó mucho mejor de manera consistente. –

+0

también terminé usando json para solucionar este problema, gracias. – botbot

4

también funcionaría respond_with {:uuid => @p.uuid}, :location => nil