At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, , ,

10 Most Common Rails Mistakes Developers Will Make

  • By Saravana
  • February 1, 2019
  • 1801 Views

Ruby on Rails is one of the popular open source web framework built on the Ruby language. Also, It’s very popular for it’s MVC architecture and community support. Rails is following the convention over configuration approach and its own set of standard conventions for naming, structure and configurations.
As we Rails developers know Rails is a very easy to use development framework but at the same time it’s often projected as too tough to handle because some of us using wrong approach while handling it. So, i wanted to make a precise list of mistakes that Rails developers will commit. While am googling the internet, most of the articles i came across has covered a very basic mistakes like MVC handling & excess usage of GEMS.
But that’s not what we exactly wanted to predict, there are some mistakes which we developers will unknowingly commit but that will totally stop us from getting into the application flow and often affect the productivity which is totally not advisable for the growing organizations.

1. Choose Correct Rails Application For Your Requirement

I have come across few rails 5 web services(API) application and still using traditional Rails web application. You may ask what’s the point of using traditional Rails when you have all the latest one’s?
The reason is Rails 5 now introduced API mode which is completely dedicated to build Rails API. If you don’t know yet then you can run the below command to create API application,

rails new [api_name]  --api

It excludes the unused and unnecessary set of middleware like views, assets etc. It starts the application with few required middleware instead of loading unnecessary code libraries.
So before creating your application analyse the purpose of the application. If you’re planning to develop web application then go with traditional Rails web application. If you are going to build only API then go with API mode application.

2. Follow Proper Naming Convention In Rails

Rails architecture have set of naming convention to make your work easy. Most of the time you are interacting with Active record models and it’s doing the database Read & Write operations. But did you know or tried to analyzed how this interaction is happening in the background.
I knew most will say “What question is that? It’s ORM which is doing all this Job”. Yes, you are correct!, But how ORM is doing this job for you?. If you’re smart enough you must know to say, it works based on the name of Activerecord Model & with the ActiveRecord model name, it’s mapping the table and doing further operation for your query and am glad if you knew it.
While doing code keep the following points in your mind.

  1. Table names should be in plural format to map your model and table automatically and if not you have to map the table with model manually.
  2. Model name should be in singular, If not again you have to map the table manually. Also make sure you are not using reserved names for your class. For example you can’t use “Class” but you can use “Klass”.
  3. Controller name should be plural format and if you want to use multiple words then go with Camelcase
  4. Follow the default restful routes to reduce the complexity.

 

3. Managing Database Schema

Rails supports Active Record Migrations to manage all your database schema instead of dealing with raw SQL. Migration files are stored with timestamp, It’s tells which migration file should run first.
In any case if you want to add, modify and remove any of your existing schema write a new migration file. Don’t change in the existing file even if it’s a small change.
Understand the use case for Change vs Up Down methods better, When you run rollback Change method, it will handle automatic revert so you no need to write separate down method.

class AddImageToUsers < ActiveRecord::Migration
 def change
add_column :languages, :ruby, :string
 end    
end

 
Basically, Up Down methods supports the custom changes like running SQL.

class AddImageToUsers < ActiveRecord::Migration
 def up
add_column :languages, :ruby, :string
Language.update_all(ruby: 'Rails')
 end
 
 def down
remove_column :languages, :ruby
 end  
end

 

4. Mistakes We commit In Rails ActiveRecord

ActiveRecord is great ORM feature in Ruby on Rails which will map models and database tables. ActiveRecord providing many methods to do perform your database I/O operations. While building your application architecture keep an eye on your future scope and challenges.
Many developers don’t understand how ActiveRecord works in rails. This may cause performance issue in your application.
For example,
To check the record availability what query you will use?
If my perspective is correct most of the people will prefer to use either one of this options,
Option 1:

User.where(is_active: true).count > 0
=> SELECT COUNT(*) FROM "users" WHERE "users"."is_active" = $1  [["is_active", "t"]]

 
Option 2:

User.where(is_active: true).any?
=> SELECT  1 AS one FROM "users" WHERE "users"."is_active" = $1 LIMIT $2  [["is_active", "t"], ["LIMIT", 1]]

So here, which one is best for checking the record availability? In opinion, I will say Option 2 is optimized one in my use case.
Wondering why i mentioned Option 2? Yes! there is a reason! Here we are checking the availability of particular case. So just checking availability is enough. No need to check the count and find the availability. So its advisable to use right option based on your use case.

5. Do You Check N + 1 Query Rails

N + 1 is the common mistake most developers will miss to fix in their code. It won’t throw any issue in the application also it will affect your application performance. So many developers won’t concentrate on this kind of performance tweaks.
So, what N + 1 issues and how you can avoid it,
You can avoid N + 1 issues when doing query for associated records. For example,

users = User.where(is_active: true)
names = users.map { |user| user.profile.name }

 
Above code block is having N + 1 issue, First it will query the users list then in the loop it will execute the query to find the user profile. If the users object holding 10 users data then the loop will execute 10 queries for that profile.
To avoid this you can use the below code,

users = User.where(is_active: true).includes(:profile)
names = users.map { |user| user.profile.name }

 
This code block will execute only two queries, One is to find the users and other one is to get the users profile and remember it won’t execute N + 1 times.

Related: 10 Useful Ruby On Rails Gems We Couldn’t Live Without

 

6. Write Maintainable Code & Perform Rails Code Optimization

First, What is maintainable code?
It means your code should be organized and easy to accommodate any further modifications. Then what is optimized code? It means your code should perform well like a boss even when its handling huge load.
Rails offers many inbuilt structures to maintain your code, here are few major things you must know,
So don’t dump everything in MVC (Model, View & Controller). For example, Model should only have the DB operations(Many developers do the calculations and other stuffs in model).
View should have the templates alone(Don’t add condition checks in view & try to use rails helpers for doing conditions and calculations).
Controller should handle only request and response (Many developers are using controllers for designing response structure and other stuffs).

7. Make Use Of Rails Error Tracking Tools

Production application is like a closed room! You can’t monitor or track everything that’s happening in your application. So its always best to add CCTV(Error tracking tool) to monitor & track your application.
In our production application we have faced this issue. Our customers will often raise issues on different places. But when we try the same scenario we can’t reproduce it. We did lot of troubleshooting to find the cause.
You may have some good tests and you may be quiet confident about your code but you can’t always understand your users usability and their inputs. even your application may have a chance to break sometime so you have to know what’s happening inside of your application.
Even we didn’t had any error tracking tools previously because we have had very good tests for our code. But sometimes, still our application got issues and we took quiet long to analyze the issue. So we decided to add error tracking tools in our application and i could say that’s one of the best thing we did for our projects. These tools are greatly helping us to identify the exact issues in short time & that also results in increased productivity.
Below are some of the popular error tracking tools you can try them out,

Also Check: How To Integrate Rails Application With Sentry – Rails Error Tracking

 

8. Use Proper Active Record Callbacks In Rails

Activerecord callbacks are awesome feature for writing hooks to do some Rails operations when the object is created, updated and destroyed.
Choose proper callback function based on your use case. Don’t use unrelated callback function.
For example you can have a look into a below sample,

class User < ApplicationRecord
     after_save :send_welcome_email
     private
           def send_welcome_email
       UserEmail.wecome_mail(user).deliver_now if self.new_record?
end
end

 
Here you can note that we have created welcome mail using after_save but i could say here this method is unrelated to the use case because after_save will execute the call back function every time we update/save the details which we necessarily don’t need.
So what call back function you can use to solve this?
Using after_create callback function you can avoid this problem. For example, check the below code

class User < ApplicationRecord
     after_create :send_welcome_email
    private
           def send_welcome_email
       UserEmail.wecome_mail(user).deliver_now
end
end

 
Also many developers are still confusing the functionalities of Active callback methods, may be they are not clear about it, so if you’re the one among them then here is the clear here’s what you should know,
after_create – Will execute on new objects that haven‘t been saved yet
after_save – Will execute after object save on both new and existing object
after_commit – Will execute after database transaction is completed.

9. Keep Your Configurations Safe

You application may have many account details / configurations for external services like AWS, Google, Facebook and lot more. So, how you are securing these details from the intruders?
I have seen so many developers who still commit configuration in version controls. If that a case, just imagine what will happen if this key and other configuration details got to the hands of unknown persons. The impact is un predictable and hard to solve, therefore always make sure to secure your private configurations and don’t ever commit it in version control.

10. Managing Proper Documentation For Code And Deployment

Being a Devops developer I have faced this issue many times. Most of the developers will have vast knowledge in development they can answer all of our queries in a glimpse of a look regardless of the project they involved in. But when it comes to preparing deployment document they fail to do their best. Please remember, making a perfect deployment document is what matters for any project because even if you have not touched the blog for years, still you can able to touch the project without having to worry much.
Alongside, while doing deployment there’s also possibility to miss some configurations so as the result it might cause the problem during deployment. so, make sure to do a proper deployment documentation including master data configuration, Cron setup, Mailer setup etc.
Reached to the end. Hope these blog helps you to have a better understanding in Rails development and if i missed out anything that you think worth adding to the list then please post your suggestions in comments. We like to hear from you to serve you better. Also you can hear more tips from the experts here. Enjoy reading!
[contact-form-7 404 "Not Found"]

Saravana

An enthusiastic Tech Lead with 7 plus years of experience in Web development arena. Owns legitimate experience in Ruby, Ruby On Rails, AngularJs, DevOps. Golang, Another add on, This young tech freak never miss a chance to get his hands on planting and Gardening even in his busy weekends.