after_create vs after_save vs after_commit

after_save, after_create and after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.

The purpose of each as per rails docs:

Is called after on new objects that haven‘t been saved yet (no record exists)

Is called after (regardless of whether it‘s a create or update save)

Is called after the database transaction is completed.

Now to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.

When rails execute a create, the after_save and after_create would be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and after_save block.

Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.

Read More

Enable log rotation within the rails application

Bookmark and Share

Any person who has worked with a rails application for a good amount of time would have faced the issue of log files growing and consuming the entire space in the hard disk. Although this sounds funny, it does happen if you do not place a log management for your rails app (in production). You can manage your logs using log rotation. Do note that log rotation is not required if you host your app in heroku, as heroku won’t let you store files for more than 15 minutes in their server. You also do not need it if you are using some third party services like loggly or papertrail to manage your logs .

In the unix world, you can use log rotate service, which would be installed by default in all linux servers. But we at Red Panthers feel that everything that touches or involves our rails application should be placed along with our rails application as much as possible. If you feel the same way, it can be achieved by placing the code below in the production.rb file.

The accepts three parameters:

  • The file name, which would be production.log
  • The number of files you want to keep
  • The size of …
  • Read More

    Skip unnecessary files while running Rails Generate

    Rails Generate is one of the features provided by Rails that would speed up the application development. However, we won’t be needing all the files generated by rails when running the generate command.

    For example:

    rails generate controller Home Index new create,  would create the following set of files:


    As one knows from experience, the helper; javascript and stylesheet files are not always used. In fact, most of the time, we would have a single stye.scss, and that would take care of 95% of the total behaviour of our application. So, if we do not delete those files after generation, we would just end up with a lot of files in our system which would have no code throughout the life cycle of the program.

    Fortunately, rails gives us the ability to customize its own generators so that we can disable these files from being generated. Once we place the below code in the application.rb, it will stop the generation of these extra files.

    Now, when you run rails generate controller Home Index new create, you will get less files.


    Read More

    God Class: Breaking Single Responsibility Principle

              “God object: In object-oriented programming, is an object that knows too much or                  does too much.” 

    – Source: Wikipedia

    God class in OOP doesn’t stand for a good thing; here it’s called an anti-pattern. In Object Oriented Programming, we create a new class to define the properties and capabilities of an object. It is using these objects that we build our system, mimicking how it would work in the real world.

    For example: Let’s assume that we are trying to build a software to manage the office of a school.

    In a typical school office, there would be different departments to handle different parts of the administration. For example, the Purchase department for the purchases, the Accounts department for the accounts, the Records department for the records, the HR department to manage the staff. When one department wants something from another department, it would ask that department for the information. As per protocol, it shouldn’t take the files from the other department without the staff or the department lending it.

    So, mimicking the real world would mean that we build one class for each department of the office. We should build a class called Accounting, and in that class we will write all the functions that the Accounts department does, and only what it does. We will not write the functions for the HR department in the account class. Keeping all the code for a particular function at a single place makes our code more efficient and cleaner. Now every time we want the Accounts department to do something, we will create an object of that class and pass the data we have to get the information we need.

    Note: In an actual …

    Read More

    Counter Cache: How to get started

    Displaying the number of tasks under a project or the number of comments in a post or the number of users in an organization or anything similar is a common requirement in most rails applications. The code for doing it is also simple- @project.tasks.count; but the problem with this code is that every time you run it, you are counting the number of tasks of that project one by one. So, the speed of execution decreases with more number of rows. This code will slow down your page load, if you are displaying the details of more than one project in your page as shown below.


    To speed this up, rails gives you an in-build mechanism called “Counter Cache“. As the name suggests, it literally means to cache the number of referenced rows it has (number of tasks a project has).

    Example code definition

    To implement counter_cache, you need to pass in the counter_cache: true option along with the belongs_to relationship. You also need to add a migration to add an extra column called tasks_count to store the count. This needs to be added to the other model, which has the has_many reference.


    If you are adding counter cache to an existing system, you need to update your tasks_count with the existing counts. To do that, one can use the code given below. Either place the code along with the migration or run it in console in both production/development environments.

    Also note that the tasks_count is just the default column name; if you wish to change it with another name, just pass that name along with the :counter_cache option as below.

    Now, to use the counter cache in your calculations, you should use the method “size” instead of “count”. The method “size” will use the counter_cache if its present, where as using “.count” itself would do the actual sql count.

    Points to Remember

    • :counter_cache is the optional attribute of a belongs_to relationship
    • It …
    Read More