This method is called upon a POST request. In general, the method is clear. But what does the string format.json {} do?

  def create @product = Product.new(product_params) respond_to do |format| if @product.save format.html { redirect_to @product, notice: 'Product was successfully created.' } format.json { render :show, status: :created, location: @product } else format.html { render :new } format.json { render json: @product.errors, status: :unprocessable_entity } end end end 

    1 answer 1

    This way of organizing a response allows you to return different answers, depending on the format of the request (issued as an extension), if this is a regular HTML request.

     POST /products 

    then the format.html block comes into format.html after the successful saving is performed by redirect_to redirect_to , or in the event of an error the form is re-rendered (where an error message is likely to be displayed). If JSON is requested

     POST /products.json 

    this is where format.json works and instead of redirects, you send back JSON responses.

    This separation of logic is often used when you have AJAX and the usual handling of the same form.

    • I assumed also, but requests are sent to POST / products and POST / products.json (I don’t know why). And how to send json request? - jisecayeyo 5:38 pm
    • @jisecayeyo In general, there is no check if if request.xhr? it means simply adding the .json extension at the end of the query, as you have in the second version. You can clarify the routes either through the config / routes.rb file or through the rake routes rake command. - cheops
    • The request is sent by pressing the buttons, so it’s impossible to send json through the address. If in config / routes.rb to register, for example, post '/ products / new', to: 'products # create', then it will generate an error that there is no POST / products - jisecayeyo
    • The button probably has a form or if it <a> has an address that the helper probably fills, almost all the helpers allow the transmission of additional parameters, including the format:: json - cheops pm
    • Do you want to override the routes? This is possible, but it is better to ask a new question in which to describe in detail what you have for the routs now and what you want to receive. - cheops