Rails: responder a JSON y HTML


Tengo un controlador "UserController" que debería responder a peticiones normales y ajax a http://localhost:3000/user/3.

Cuando se trata de una petición normal, quiero mostrar mi vista. Cuando se trata de una solicitud AJAX, quiero devolver JSON.

El enfoque correcto parece ser un bloque respond_to do |format|. Escribir el JSON es fácil, pero ¿cómo puedo hacer que responda al HTML y simplemente renderice la vista como de costumbre?

  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html {
        render :show ????this seems unnecessary. Can it be eliminated??? 
      }
      format.json { 
        render json: @user
      }
    end
  end
Author: Don P, 2013-11-25

3 answers

Según mi conocimiento, no es necesario "renderizar show" en formato.html buscará automáticamente una vista de acción respectiva para ex: show.HTML.erb para solicitud html y show, js, erb para solicitud JS.

Así que esto funcionará

respond_to do |format|

  format.html # show.html.erb
  format.json { render json: @user }

 end

Además, puede comprobar que la solicitud es ajax o no marcando solicitud.xhr? devuelve true si la solicitud es ajax.

 70
Author: Amitkumar Jha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-25 08:53:04

Sí, puede cambiarlo a

respond_to do |format|
  format.html
  format.json { render json: @user }
end
 16
Author: Santhosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-06 03:25:03

La mejor manera de hacer esto es como dijo Amitkumar Jha, pero si necesita una forma simple y rápida de renderizar sus objetos, también puede usar este "atajo":

def index
  @users = User.all
  respond_to :html, :json, :xml
end

O hacer que respond_to funcione para todas las acciones en el controlador usando respond_with:

class UserController < ApplicationController
  respond_to :html, :json, :xml

  def index
    @users = User.all
    respond_with(@users)
  end
end

A partir de la versión Rails 4.2 necesitarás usar gem responder para poder usar respond_with.

Si necesita más control y desea poder tener algunas acciones que actúan de manera diferente, siempre use un respond_to completo bloque. Puedes leer más aquí.

 0
Author: Nesha Zoric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 13:55:14