-1

I am new to rails and am confused about the format.json lines in the code below. What do status: :created and location: @product refer to?

def create
      @product = Product.new(params[:product])

  respond_to do |format|
    if @product.save
      format.html { redirect_to @product, notice: 'Product was successfully created.' }
      format.json { render json: @product, status: :created, location: @product }
      format.js
    else
      format.html { render action: "new" }
      format.json { render json: @product.errors, status: :unprocessable_entity }
      format.js
    end
  end
end

Is including status and location optional? I'm mostly confused about what is optional and why one might add a custom status/location.

Kenny Zhang
  • 63
  • 2
  • 11
  • 2
    Possible duplicate of [What does \`:location => ...\` and \`head :ok\` mean in the 'respond\_to' format statement?](http://stackoverflow.com/questions/5213956/what-does-location-and-head-ok-mean-in-the-respond-to-format-stat) – Ramesh Kumar Thiyagarajan Jan 23 '16 at 18:21

2 Answers2

0
  • status: :created means HTTP status of rails app response - it is 201 in integer representation. List of HTTP statuses here
  • location: @product in fact generates url to show action of ProductsController like product_path(@product) and set HTTP location header of response. Means that resource could be retrieved on given location URL with HTTP GET request, more information here
Semjon
  • 983
  • 6
  • 17
  • is adding status and location optional? and why? thanks – Kenny Zhang Jan 23 '16 at 18:32
  • That is optional, but correct status and location are parts of HTTP specifications. It is always good to follow them and keep application as much standard as possible. For example, this JSON API may be utilized by client-side JS application or mobile application. For developers it would more easy to work with standard interface rather than custom. Keep in mind the main Ruby principle - "Less surprise behaviour" :) – Semjon Jan 23 '16 at 18:55
0

If very easy.

you can send difference request formats - html (default), json, js, etc

by default action wait for html request, and action will be confused if it will get, for example json. So for avoiding this you have to add format.json {} and in braces you add information what you wanna render.

EDIT

more detail you can READ HEAR

Oleh Sobchuk
  • 3,612
  • 2
  • 25
  • 41