3

So I have been going through Rails Zombies and have gotten to the part explaining format.html and .json My question is what do these lines of code do, and why do we have them? If I write these methods or actions without these format codes they work perfectly fine, as i'd assume they simply display in html format by default? If somebody could clear up exactly what this code does I'd be grateful, I also do not fully understand what JSON is.

def create
    @zombie = Zombie.new(zombie_params)

    respond_to do |format|
      if @zombie.save
        format.html { redirect_to @zombie, notice: 'Zombie was successfully created.' }
        format.json { render :show, status: :created, location: @zombie }
      else
        format.html { render :new }
        format.json { render json: @zombie.errors, status: :unprocessable_entity }
      end
    end

1 Answer 1

2

In simple terms:

If the request wants an HTML page, it will perform the instructions set by the block given to format.html.

If the request wants application/json (like when you make an Ajax request), the response will be given as instructed in the block given to format.json.

You should know what JSON means before delving into creating any web service. See http://www.json.org/

Sign up to request clarification or add additional context in comments.

5 Comments

Actually you will use format.js for Ajax requests, format.json is more suitable for an API.
So when would I use JSON and why?
JSON is the preferred way nowadays to serve data from a web service. In the past people liked to use XML. But now JSON has taken over. You should really learn about it first before going full force into web development. Also, read about SOA, Service Oriented Architecture.
An example of a fake API that serves json: jsonplaceholder.typicode.com Try their endpoints, for instance jsonplaceholder.typicode.com/users
@nbkhope thank you very much this has cleared up lots for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.