paint-brush
Top 10 Most Common Ruby on Rails Errors and Their Causesby@abubakar-diallo
925 reads
925 reads

Top 10 Most Common Ruby on Rails Errors and Their Causes

by Abubakar DialloJune 30th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Ruby on rails is an open source full-stack web application framework written in Ruby. It follows the popular MVC framework model and is known for its "convention over configuration" approach to application development. In the process of developing ruby on rails applications, there are occurrences of errors that have been taken note of. By grouping errors according to fingerprinting, errors made in projects are being detected and collected with the help of the rollbar and the top 10 errors made by developers have been as well detected based on the frequency of occurrence of each error.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Top 10 Most Common Ruby on Rails Errors and Their Causes
Abubakar Diallo HackerNoon profile picture

Before any exposition could be made concerning rails errors and their causes, it is of great importance to know what ruby on rails is all about.

Ruby on Rails is an open source full-stack web application framework written in Ruby. It follows the popular MVC framework model and is known for its "convention over configuration" approach to application development. In the process of developing ruby on rails applications, there are occurrences of errors that have been taken note of.

By grouping errors according to fingerprinting, errors made in projects are being detected and collected with the help of the rollbar and the top 10 errors made by developers have been as well detected based on the frequency of occurrence of each error.

Therefore, from a close observation on thousands of ruby on rails project by developers, below are the top 10 errors that developers commit in their development scheme.

1. ActionController::RoutingError

The first error we're examining is the ActionController::RoutingError. This kind of error occur when a user has requested a URL that doesn’t exist in his/her application. This error might occur because an incorrect link is pointing at your application or on the other hand pointing from within your application. It could also be caused by your application being bot tested for common weaknesses.

ActionController::RoutingError (No route matches [GET] "/wp-admin"):

Whenever you experience or come across this type of error, it most commonly occur due the application being used and not by errant users. If you deploy your application to Heroku or any other platform that doesn't permit you serving static files, you might therefore have your CSS and JavaScript not being able to load. If this is the case, the errors will appear like this:

ActionController::RoutingError (No route matches [GET] "/assets/application-eff78fd93759795a7be3aa21209b0bd2.css"):

This error could therefore be fixed by adding a line to your application's

config/environments/production.rb
as written below:

Rails.application.configure do
  config.public_file_server.enabled = true
end

You might also decide not to go by logging 404 errors caused by

ActionController::RoutingError
but instead set a catch on all routes and serve the 404 yourself. If you're interested in doing this, then you add the line written below at the bottom of your
config/routes.rb
file as suggested by Lograge project:

Rails.application.routes.draw do
  # all your other routes
  match '*unmatched', to: 'application#route_not_found', via: :all
end

Be sure to use this method only when you're sure that knowing 404 errors is important to you.

2. NoMethodError: undefined method '[]' for nil:NilClass

Sometimes, when parsing and extracting data from a JSON API or a CSV file, or when trying to get data from nested parameters in a controller action, errors do occur due to nil or missing object when you are using square bracket notation to read a property from an object.

You can fix this error by performing a nil check on each parameter and more efficiently, there is an alternative way to access nested elements in hashes, arrays and event objects like

ActionController::Parameters
.

We know that Ruby 2.3, hashes, arrays and

ActionController::Parameters
have the dig method. and dig helps to create a path to an object that is to be retrieved. Therefore, if in the process, nil is returned, then dig returns nil without throwing a NoMethodError.

3. ActionController::InvalidAuthenticityToken

Although there might be other reasons why you're experiencing this error on your application, it commonly occur due to the fact that an attacker is targeting the user of your site but the rail security measures are keeping you safe. In a case where POST, PUT, PATCH or DELETE is missing or has an incorrect CSRF token, then the error is said to be in place. Careful measures are needed to be taken since this error type is one which deals with your application's security.

You therefore can turn off your CSRF protection but sometimes, you expect to receive incoming posts request to certain URLs in your application. Therefore you can turn off CSRF protection but ensure that you are whistling the end point you know don't need the protection since you wouldn't want to block them (the third parties) on CSRF basis. You can accomplish this by skipping the authentication.

4. Net::ReadTimeout

When it takes ruby longer time to read data from a socket than the Read_Timeout value, then the

Net::ReadTimeout
issue arises. There are more than one ways through which one can fix this error. You can adjust the read_timeout value to something more sensible provided that you understand the HTTP requests that are throwing the error. This particular error can arise if you're using Net::HTTP, open-uri or HTTParty to make HTTP requests. Just as it's being written, , if the server you are making the request to takes a long time to put together a response before sending it all at once, you will want a longer read_timeout value. If the server returns the response in chunks then you will want a shorter read_timeout.

5. ActiveRecord::RecordNotUnique: PG::UniqueViolation

Right in your application, there is a certain database table that has a unique index on one or more field, this error would definitely occur if a transaction that violate the database is sent to it. This particular error message is therefore basically for PostgreSQL databases, but the ActiveRecord adapters for MySQL and SQLite will throw similar errors.

If the errors are caused by a race condition, that may be because a user has submitted a form twice by mistake. We can try to mitigate that issue with a bit of JavaScript to disable the submit button after the first click. You start by introducing something like this:

const forms = document.querySelectorAll('form');
Array.from(forms).forEach((form) => {
  form.addEventListener('submit', (event) => {
    const buttons = form.querySelectorAll('button, input[type=submit]')
    Array.from(buttons).forEach((button) => {
      button.setAttribute('disabled', 'disabled');
    });
  });
});

6. NoMethodError: undefined method 'id' for nil:NilClass

Unlike the error type explained earlier in number 2, these errors arises when validation fails, it (the error) usually sneaks up around the create action for an object with a relation. This error come in place when you call 

render :new
 from the create action, the 
@courseinstance
variable wasn't set.

You therefore need to ensure that all the objects the new template needs are initialized in the create action. You can fix this problem by updating the create action to look like this;

def create
    @course_application = CourseApplication.new(course_application_params)
    if @course_application.save
      redirect_to @course_application, notice: 'Application submitted'
    else
      @course = Course.find(params[:course_id])
      render :new
   end
end

7. ActionController::ParameterMissing

Among of the rails strong parameters is this error. If you are building an application to be used via a web front end and you have built a form to correctly post the user parameters to this action, then a missing user parameter probably means someone is messing with your application. In this case, it's more likely that a 400 Bad Request would be best to be responded with. It usually does not occur or manifest as a 500 error.

The full error might look like this:

ActionController::ParameterMissing: param is missing or the value is empty: user

8. ActionView::Template::Error: undefined local variable or method

Error in this manner occur when a variable or method you believe or expect to exist does not. Among the top 10 commonly made errors that we're discussing, this is the only ActionView error. This instill that the less work the views have to do to render templates, the better as lesser works doesn't seem to have much errors.

9. ActionController::UnknownFormat

Simply speaking, this particular error occur due to the carelessness of users and not the application. Taken for instance, in a case whereby you built an application of which actions responds with HTML template and someone requests the JSON version of the page, the error tends to surface. You can therefore build your rails applications to respond to regular HTML requests and more API-like JSON requests in the same controller. By doing this, you define the formats you wish to respond to and any formats that is not in line with it will still bring about ActionController::UnknownFormat error thereby returning a 406 status.

10. StandardError: An error has occurred, this and all later migrations
canceled

Even though Standard error should be the parent errors to these errors we've been talking about but in reality, it is an error that only happened during a database migration. One of the reasons why you experience this error might be that your migrations may have gotten out of sync with your actual production database and in this case for instance, you will have to go dig around to find out what the problem is and fix it. If you want to add or calculate some data for all objects in a table, then data migration might seem to be a good option.

Take for instance, if you want to add a full name field to a user model that included their first and last name (not a likely change, but good enough for a simple example), your migration might seem like this:

class AddFullNameToUser < ActiveRecord::Migration
  def up
    add_column :users, :full_name, :string
    User.find_each do |user|
      user.full_name = "#{user.first_name} #{user.last_name}"
      user.save!
    end
  end
  def down
    remove_column :users, :full_name
  end
end

Conclusively, the most popular rail errors can come from anywhere within the application. Even though these errors in a way serves as protection to our application, it is therefore unwise not to try get these errors caught and get them stamped out. It would help you detect and fix the problem as an engineer or product manager before users lodge the complains themselves.