Skip to main content

Ruby on Rails 5 - 204 No Content - Why this change makes sense for you?

Note: This is a change that is present in the latest Rails version 5. Versions before the 5 will throw an error "MissingTemplate" exception.


In Ruby on Rails 5, there is a change that is particularly important. Rails server issues a HTTP code of 204 No Content when you request a POST method without a template but the action for the same is present. This happens only when the HTTP Verb is POST and it doesn't happen for GET requests.

This is the sample code for the action which will be called as POST:


def create

  @user = User.new(params[:user])

end

So how does this help you?

  1. Now you can write your own POST actions which can be called via Ajax calls which will automatically get a success response because of the 204 http code and you can let your javascript handle the changes on the UI.
  2. GET via browser will throw an error. This is because Rails assumes that you have to have a template for showing some content to the user.

Any disadvantages?

  1. Your html page after the POST request will be still the same and the page won't transition to a new page. This means that it will look like nothing has been done by the server and the user might be confused if its a form POST.


Thanks for your support and appreciation.

You can also follow me at Twitter, Facebook, LinkedIn and Website.

Comments

Rathnam said…
I was wondering why. This answered it. thanks...

Featured

Rails Engine - How To Keep Your Engine Migrations Abstracted From Your Host Rails App

Have you ever worked on building a Rails Engine and wanted to keep the models, the migrations and everything inside the engine rather than using a generator to copy paste them into your host Rails App? That's a problem everybody faces one time or the other when building Rails Engines to abstract out your huge Rails App. I have found one such solutions that can be helpful for you to keep them separate. Here is a solution for it.
Problem Statement: Instead of using

    rails g my_engine:install
to copy paste the migrations from engine to your rails app, you want to just keep the migrations inside the Rails Engine and do not bother about it.
Solution:  Add the following lines to your engine, so that your engine's migration files are added to the rails app as well.

Now you can do the following from your rails app to run your migrations as you always do:

rake db:migrate
Hope it helps you! If it does help you, give me a shoutout below!

Talk to me on Twitter, Facebook, LinkedIn or Web…
You will receive wonderful short stories written by him and inspirational articles once every month.