Leo Leo - 2 months ago 13
JSON Question

Why "format.json { render :show }" doesn't work?

I've been following along with the book Agile web development with rails4. The following code is a little confusing:

respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: @line_item }
...


I am not sure whether this line

format.json { render :show, status: :created, location: @line_item }


really work because I cannot find any json content through the inspect tool of the chrome browser.

Also, the "render :show" seems to reference to the jbuilder:

views/line_items/show.json.jbuilder


I tryed to add some "p ..." in this show.json.jbuilder but I failed to see any output in the terminal.

Answer

In the respond_to block, only one of those format... lines will run and it depends on the type of request. The format.json line will only run if the initial request was an ajax request. If the request was a normal form submission, then only the format.html line is used.