Most Common Mistakes To Avoid In Ruby On Rails Development

Most common mistakes to avoid in ruby on rails development

Ruby on Rails is a popular web framework that allows you to build scalable, enterprise-ready applications with complete front-end support. Rails is following the convention over configuration approach and its own set of standard conventions for naming, structure and configurations. Rails is an easy to use development framework but some of it’s projects are tough to manage due to the some wrong approaches that we are using while handling it. So here we’ve listed some common mistakes that Rails developers commit. 

Most common mistakes in ruby on rails development-

1. Not using the correct rails application for your requirement-

Most of the web services apps are still using a traditional Rails web application. Why? What is the reason to use traditional Rials when you have all the latest one’s? New versions of Rails introduced API mode that is completely dedicated to build Rails API. If you don’t know then you can run the following command to create API app, 

rails new [api_name]  --api

It executes the unused and superfluous set of middleware like views, assets and so on. It starts the application with some needed middleware instead of loading unnecessary code libraries. Hence before starting development of your app analyse the purpose of application. If you’re thinking to develop web app then prefer the traditional rails web application. But if you’re building only API then prefer API mode application.

2. Putting too much logic in the controller-

We all know that Rails is based on MVC architecture. Moving view logic or domain/model logic into controller is easy. But the problem is, Controller object will start violating the single responsibility principle that makes future changes to the code base difficult and error-prone. Generally, the only types of logic should be in your controller are:

  • Session and cookie handling- This may include authentication/authorization or any extra cookie processing you have to do.
  • Request parameter management- Collecting request parameters and calling appropriate model method to persist them.
  • Rendering/redirecting- Rendering the result(html, xml, json etc) or redirecting as appropriate.
  • Model selection- Logic for finding the right model object given the parameters passed in from the request. Ideally this should be a call to a single find method setting an instance variable to be used later to deliver the response.

This still pushes the limits of single responsibility principle, it’s kind of a bare minimum that the rails framework needs us to have in the controller.

3. Excessive use of RubyGems-

RoR developers are lucky because they get a large number of gems to ease development. But some of the developers make excessive use of gems in their applications to the extent that gems’ use is more than functionality of the app.  The main issue that arises from Gems’ excessive use is that your web app’s size increases and this reduces the app performance. Also, it requires more memory configurations and increased optimization costs. So your rails app takes more time to start that reduces development time. Also with each gem you add, dependency on another gem includes. So you increase the number of dependencies in your app, that creates lags in application. This is called the compounding effect. For instance, using a gem rails_admin creates dependencies for 11 more gems. So you should consider this before you use a gem.

4. Mistakes we commit in Rails ActiveRecord-

ActiveRecord is a great ORM feature in Ruby on Rails that will map database tables and models. It provides lot of methods to carry out database I/O operations. You must focus on future scope and challenges while building app architecture. Most of the developers don’t understand the working of ActiveRecord in rails. This can cause the performance issue in application.

For example, to check the record availability what query you will use? Here most of the developers will prefer to use either one of the 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]]

Which option is best to check record availability? Option 1 or Option 2?  Option 2 is better. Why? There is a reason! Here we’re checking the availability of specific case. So only checking availability is not sufficient. No compelling reason to check the tally and discover the accessibility. So it’s prefer to use right option based on your use case.

5. Blocking on calls to external services-

Third party providers of Ruby on Rails apps eases the APIs integration bust sometimes it may run slow. To avoid blocking on calls, instead of calling services from your Rails app, you should move some part of code to background task. To query these API services, you should use Delayed Job, Sidekiq and so on.

6. Improper predicate method usage-

Predicate method is a method that syntactically ends with question mark and should return a true value. When you create a predicate method, it is necessary to know its main purpose. It should be named for what it performs, it should not contradict the name with the action it performs.

For eg., check  whether the user has books available or not, you should define the predicate method in user model as mentioned below-

def books_available?
    self.books.present?
end

7. Managing database schemas-

Rails supports Active Record migrations to manage all database schema rather than dealing with raw SQL. Migration files are stored with timestamp, it tells which migration file should run first. If you want to add, modify and remove existing schema write a new migration file. Don’t change in the existing file even though it is a small change. Understand the use case for change vs Up down methods better. When you run rollback change method, it will tackle automatic revert so that there is no need to write a 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

8. Using improper naming conventions-

Rails architecture has a set of naming conventions to ease your work. Many times you interact with Active record models and it’s doing the database Read and Write operations. But do you know how this interaction is happening?

It works based on the name of Activerecord Model & with the ActiveRecord model name,it’s mapping the table and doing remaining operation for your query.

Always remember the following points while doing coding-

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

9. Not using memoization:

Memoization is a technique to boost your accessor during RoR development. It catches the method results that do tedious work or variables initializing.

Use | |= operator to initialize the cache variable.

You can use it to initialize variables from some value in parameters, or associated records.

Eg:

def google_calendar_event
   @event ||= GoogleCalendarEvent.find_by(event_id: params[:event_id])
end

10. Not writing maintainable code & not perform rails code optimization-

What is maintainable code?

Means, your code must be organized and easy to accommodate further modifications. 

What is optimized code? 

Means your code should perform properly even when it  is handling a large code.

Rails offers a lot of inbuilt structures to maintain code. Know the major things-

  • Don’t put everything in MVC(Model, view & Controller).  Model should have DB operations.
  • View should have the templates alone
  • Controller should handle only request and response

Final Words-

Rails is a powerful framework for rapid development. Developers should pay attention to the potential design and coding errors to ensure that their apps are easily extensible and maintainable as they grow. To make applications reliable and secure you must be aware of these issues. 

If you are still facing issues in ruby on rails development, consult with solace experts. We are here to help you through consultation and development. You can hire ruby developers of solace team for reliable and secure development. Connect with solace and get a free quote for effective RoR development. We will be happy to help you.

Related Post