Michael Mudge
Michael Mudge

Reputation: 439

What is a .json file used for in a rails app?

What exactly is a .json file used for in a professional rails app?

I created a scaffold for my Blog and understand the CRUD actions with with postgresql DB, however I am just wondering about the format.json lines of code that are also created in a scaffold.

def create
  @blog = Blog.new(blog_params)

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

Upvotes: 0

Views: 177

Answers (1)

Frederik Spang
Frederik Spang

Reputation: 3454

JSON is a commonly used format for API's, and commonly used in Rails API's.

When you're doing format.json in the controllers, you're really saying "This route/endpoint can respond to JSON requests", and not only html requests.

When a website is viewed in a browser, your browser automatically sends along a HTTP Header called Accept. Such as:

Accept: <MIME_type>/<MIME_subtype>
Accept: <MIME_type>/*
Accept: */*

This may be any number of MIME-Types; Including Accept: application/json, which will tell Rails, that it may respond with JSON.

What the browser does, is to send along Accept: text/html, which is perceived as "Hi, I want the HTML edition of this", thus rendering the format.html-block.

See also:

Upvotes: 5

Related Questions