Leo Leo - 1 year ago 76
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:


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download