55

I have a controller "UserController" that should respond to normal and ajax requests to http://localhost:3000/user/3.

When it is a normal request, I want to render my view. When it is an AJAX request, I want to return JSON.

The correct approach seems to be a respond_to do |format| block. Writing the JSON is easy, but how can I get it to respond to the HTML and simply render the view as usual?

  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
Don P
  • 60,113
  • 114
  • 300
  • 432
  • 5
    When you call your action url without anything, e.g. /users/3 it will return html. If you call /users/3.json - it will return json – Igor Kasyanchuk Nov 25 '13 at 08:45

3 Answers3

105

As per my knowledge its not necessary to "render show" in format.html it will automatically look for a respective action view for ex : show.html.erb for html request and show,js,erb for JS request.

so this will work

respond_to do |format|

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

 end

also, you can check the request is ajax or not by checking request.xhr? it returns true if request is a ajax one.

Amitkumar Jha
  • 1,313
  • 1
  • 10
  • 15
22

Yes, you can change it to

respond_to do |format|
  format.html
  format.json { render json: @user }
end
Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
Santhosh
  • 28,097
  • 9
  • 82
  • 87
0

The best way to do this is just like Amitkumar Jha said, but if you need a simple and quick way to render your objects, you can also use this "shortcut":

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

Or make respond_to work for all the actions in the controller using respond_with :

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

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

Starting from Rails 4.2 version you will need to use gem responder to be able to use respond_with.

If you need more control and want to be able to have a few actions that act differently, always use a full respond_to block. You can read more here.

Nesha Zoric
  • 6,218
  • 42
  • 34
  • The shortcut notation doesn't work for me. Do I need some extra configuration? – wensveen Aug 27 '19 at 07:22
  • @wensveen Please leave additional information in case somebody or me can answer. – Nesha Zoric Aug 27 '19 at 11:26
  • 1
    I'm fairly new to Ruby and Rails. When I use the "shortcut" Rails gives an error about a missing template. I have a template for html, but expected json to be handled automatically. It does work when I use respond_with or use the respond_to block with `render json:` – wensveen Aug 28 '19 at 13:33