Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: respond_to JSON and HTML

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 
like image 859
Don P Avatar asked Nov 25 '13 08:11

Don P


2 Answers

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.

like image 103
Amitkumar Jha Avatar answered Sep 20 '22 09:09

Amitkumar Jha


Yes, you can change it to

respond_to do |format|   format.html   format.json { render json: @user } end 
like image 29
Santhosh Avatar answered Sep 22 '22 09:09

Santhosh