Rails Best Practices followed in RailsFactory


Needless to say, if an application does its job well and good without any bugs showing up, the credit goes to its developer. It’s not just that the code written for the application is correct; it has to be written “properly”. Properly means, not only without bugs and errors, but it must be written to suit and satisfy the coding standards of that particular language or framework the application was built on. It must also be easy to edit, maintain or debug the code for errors, if any and also must be the most secure code.

MVC Architecture

If you are into web development then you must have the knowledge about MVC architecture, the abbreviation of Model-View-Controller. As the name implies, View is the browser where the page is displayed for the user to view. Model is the database model that takes care of the details in the database, for example a table of user, with user id and the corresponding password. Controller runs the show by acting as the intermediate which connects the View and Model, holding the logics of the website.

MVC Architecture

Now, why do we need to know about this MVC? Because, application coding that are written and executed and the best practices followed in coding, are all based on this architecture only!

What is a good code?

Code when written for a larger and complex application or if done by different teams, tend to have some unnecessary complexity, repetition, and might become fragile. A code that follows the best practices, a set of procedures, is a good code which must be

  1. Readable
  2. Flexible
  3. Maintainable
  4. Consistent
  5. Testable and
  6. Effective

Mainly, a good code increases the performance of the application.

What are the best practices?

Best practices are the standard set of procedures that must be followed by a developer when writing codes for an application, to increase the performance of the application as well as make the code more clear and effective. These standard procedures vary according to the language, framework, deployment method and others, but it is a must for any application to make it a high quality solution.

Controller Coding Standards

Controller must always be thin, with codes no longer than 5-8 lines. The actions of the controller must be limited to few methods like index, new, create, edit, update or destroy. If a controller is given with more than 10 methods that might severely affect the performance of the page. Protected and private methods should be used as much as possible and should be declared at the end of the page. As the bottom line, Controller must only contain action methods and any other method can simply be loaded into a Helper and moved to Model or View.

Model Setup

Models can be heavy with logics, than the Controllers. Ideal Model structure would be like,

#====== Header Section ======
# Schema Information
# Required Files list
Class Model <ActiveRecord::Base
#====== TOP ======
# Library or Include Methods
# Model Relationships
# Virtual Attributes
# Active Record Validations
#====== MIDDLE ======
# Custom Validations
# Public Methods
#====== BASE ======
# Protected Methods
# Private Methods

You can simply select the appropriate column in a table and access the particular data, than going through every single data recorded in the table, using activerecord finder.

@users = User.ordered
class User < ActiveRecord::Base
scope : ordered, order(“last_name”)

ActiveRecord::Observer can monitor when a Model object is created or deleted. Finders should be present in their own Model.

@memberships=@user.memberships.where(:active=>true).limit(5).order(“last_active_on DESC”)

This code can be represented in Model as

class User < ActiveRecord::Base
has_many :memberships
def find_recent_active_memberships
class Membership < ActiveRecord::Base
belongs_to :user
def self.find_recently_active
where(:active => true).limit(5).order(“last_active_on DESC”)

When more than one Model is used to update the Transaction at the same time, then the code can be written as

class Account <ActiveRecord::Base
def create_account!(account_params, user_params)
transaction do
account = Account.create!(account_params)
first_user = User.new(user_params)
first_user.admin = true
self.users << first_user
return account

View Coding Standards

View files should be light weight. As they use very little ruby, View should not be used for Databases. Adding CSS and JavaScript files to the View must be avoided and only HAML should be used. Yield is used to append HTML content. When we use <%= yield :nav %> in View file, the below code is fetched from the layout.

<% content_for :nav do %>
<%= link_to “Your Account”, account_url %>
<%= link_to “Your Maps”, user_maps_url(current_user) %>
<% end %>

Consider a code as below:

In View file

<div class=”feed”>
<% if @project %>
<%= link_to “Subscribe to # { @project.name } alerts.”,
project_alerts_ur l(@project, :format => :rss),
:class => “feed_link” %>
<% else %>
<%= link_to “Subscribe to these alerts.”,
alerts_url(format => :rss),
:class => “feed_link” %>
<% end %>

In Helper Methods

def rss_link(project = nil)
content_tag :div, :class => “feed” do
content_tag :a,
“Subscribe to these
#{project.name if project} alerts.”,
:href => alerts_rss_url(project),
:class => “feed_link”

Then the code can be simplified as below:

In View File

<div class=”post” id=”post_<%= @post.id %>”>
<h2 class=”title”>Title</h2>
<div class=”body”>
Lorem ipsum dolor sit amet, consectetur…
<ol class=”comments”>
<% @post.comments.each do |comment| %>
<li class=”comment” id=”comment_<%= comment.id %>”>
<%= comment.body %>
<% end %>

In Helper Method

<%= div_for @post do %>
<h2 class=”title”>Title</h2>
<div class=”body”>
Lorem ipsum dolor sit amet, consectetur…
<ol class=”comments”>
<% @post.comments.each do |comment| %>
<%= content_tag_for :li, comment do
<%= comment.body %>
<% end %>
<% end %>
<% end %>

Pack your codes into Gems and Plugins

If you have written a generic code, that can be reused for another application, stop right there and wrap it up into a Plugin or Gem. This saves you much of your time and lets you really focus on the present problem. This also makes your code look simple enough.

Other Coding Standards Checklist

  1. Use multipart/alternative as content type of Emails
  2. Database Index should be added
  3. before_filter must be used
  4. Unused methods in Controllers must be removed
  5. Unused methods and empty Helpers must be removed
  6. Trailing white spaces, long line codes must be avoided
  7. Usage of Parantheses, Ternery operators, Constants, Translations and comments for all Classes/Methods are highly recommended
  8. Tab space must be replaced with 2 space indent
  9. Exception Handling is highly recommended
  10. Hash Syntax is a must


Literally, there are still hundreds of coding practices and techniques are available, that makes the Rails developer’s work easier. Above mentioned practices are few must be followed practices that are applicable to any project. So are you following these practices? Contact us to know more and develop your coding skills.

Comments are closed.