How to Avoid Common Ruby on Rails Errors

Ruby on Rails has caught fire since the IT community discovered how appealing and efficient it is to use — and, more important, how quick and easy Ruby on Rails makes getting new web pages and sites up and running.

Developers from all backgrounds — including .NET, Java, PHP and even newer systems — are jumping onto the Ruby on Rails bandwagon … umm, train … er, tracks … Well, you get the picture.

An open-source web framework that runs on the Ruby programming language, Ruby on Rails is an “opinionated” framework; as such, as you work, it guides you to use certain best practices. You don’t have to follow these, but your work will be considerably more hassle-free if you do.

The Ruby on Rails framework is stacked computer code, with errors showing up as very noticeable spurs. The errors show programmers an opportunity to be more efficient.

Common Ruby on Rails errors can be classified into three groups:

View Errors

The view layer takes data from the lower layers and displays it in logical structures using HTML. The following techniques can help prevent some common pitfalls in the view layer of Rails.

1. Declutter using partials: Rails’ view code makes more sense when it is decluttered into partials, and all the view logic is put in helpers. This not only helps debug errors, but it also keeps the code clean and readable. Partials can also be shared across views.

2. XSS security issues: Creating HTML tags within Ruby on Rails helpers can get messy and lead to security issues such as cross-side scripting (XSS). This can be prevented using the code content_tag.

Example (HTML without content_tag):

str = "<li class='vehicle_list'> "
str += link_to("#{vehicle.title.upcase} Sale", 
show_all_styles_path(, vehicle.url_title))
str += " </li>"

Example (HTML with content_tag):

content_tag :li, :class => 'vehicle_list' do
link_to("#{vehicle.title.upcase} Sale", 
show_all_styles_path(, vehicle.url_title))

(Thanks to Mike Perham’s “Five Common Rails Mistakes” for the sample code.)

3. ‘Yamilized’ views: Render views in YAML and parse them using YAML parser in Rails. YAML files are simple and easy to read, even by novices. Tweaking and maintaining YAML files is also very simple.

4. HTML libraries, languages and templates: HTML libraries and languages such as HAML have the look and feel of the actual HTML structure. They are easy to maintain and readable, avoiding unnecessary (and messy) HTML code. You can also use templates such as Twitter Bootstrap to make a website responsive among varied display formats, including tablets, smartphones and PCs. What’s more, switching among themes adds interest to the site.

5. Minimizing scaffolding usage: Relying on scaffolding to create Ruby on Rails apps usually provides a better understanding of the Rails framework, especially for beginners. Generating views manually gives the user more control and, over time, better understanding.

Controller Errors

The controller is the “traffic cop” in any Rails application, directing an input request either to the model for database operations or to the view to render the appropriate page with data. The following techniques help in avoiding common Ruby on Rails pitfalls and errors at the controller level.

1. Nested resources: Nesting logical resources can be a great design decision because it avoids repetition of resources and effort. For example, one event can have many nested registrations. The routes also must be modified accordingly.

2. Custom controller action: Occasionally, you’ll need to add actions to controllers that do not fit into the generic controller-action paradigm. This can be done by modifying the routes and adding the action.

3. Using ‘Get’ and ‘Post’: Use Get for those programming routes that need to be crawlable through search engines. Use Post for routes that need to mutate the database or convey sensitive information such as logins and passwords.

4. Built-in helper method: Built-in helper methods help share functionality between views and controllers.


helper_method : help_me

def help_me


Now, help_me can be accessed in the views for that controller using <% =help_me %>.

5. Removing unused resource actions: In some cases, you do not need to delete or update a resource. In those cases you can use an “except” clause in the controller to ignore those.


resources :messages, :except => [:edit, :update]

Here “edit” and “update” actions are removed from routes.

Model Errors

The model interfaces with the database for all CRUD (Create, Read, Update, Delete) operations. Active Record, the ORM (object-relational mapping) layers in rails, interfaces business logic and facilitates persistent storage (database). ORM is a generic term used in many systems, which are diverse and all mapped to unified database systems. The following techniques help in avoiding common Ruby on Rails pitfalls and errors at the model level.

1. Using schema constraints in migrations: Constraints such as :null => false , :limit => 100 and the like maintain database integrity and prevent data corrosion in the long run.

2. Raising useful errors in models: Rails standard validation errors can be customized to help the end user better understand errors.


<%= error_messages_for 'user' %>

(Add this statement to the view code in order to display custom errors.)

@user.errors.add field_name, error_message

(Add this statement to the model from the controller.)

3. Preventing giant query loading: Using find_each instead of each prevents giant queries from loading into memory. Example:

User.has_purchased(true).each do |customer|

The above query pulls all data into memory, causing excess memory usage and slowness. Using the following code prevents this issue:

User.has_purchased(true).find_each do |customer|

The above query uses find_in_batches internally, which minimizes memory load issues.

4. Skinny Controller and Fat Model: This is a good Ruby on Rails paradigm to limit the database CRUD operation and app logic to the model layer. The controller should only get and post data from and to the model and should only act as a traffic cop to route requests between the model and the views.

5. Choosing database design (STI/polymorphic): Using the right database design can improve every aspect of a Rails application. Use STI in instances where a single table is used to reflect multiple models that inherit from one single-base model.


class Comment < ActiveRecord::Base
class VideoComment < Comment
belongs_to :video, :foreign_key => "source_id"
class ProfileComment < Comment
belongs_to :profile, :foreign_key => "source_id"

Here, “comment” can be of type video or profile. Polymorphic is an extension to STI for which the implementation is much easier to create and to maintain.


class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
class Video < ActiveRecord::Base
has_many :comments, :as => :commentable
class Profile < ActiveRecord::Base
has_many :comments, :as => :commentable

In the above case, both “Video” and “Profile” have numerous comments. The commentable type distinguishes them.

These above suggestions should help make your use of Ruby on Rails simpler and smoother — and assist you in keeping your web development projects on track.

Use the comments section to share your tips and tricks for troubleshooting Ruby on Rails errors.