The Best Practices for Rails App Development

“Rails” is an amazing framework to develop web applications quickly through its inbuilt helper libraries. However, there are certain best practices that you should follow to get your rails app perform better.

Conventional programming methods:

Most developers love to place the logic inside the controller and use the model for the “Active Record” operation only.

This leads to a “Fat controller and skinny model” interface which eventually kills an app’s performance and looses the maintainability of the code. This way, application stops responding when the load is high.

What should be the best practices?

Below, I have mentioned some of the most essential and useful practices that should be followed by every Ruby on Rails developer.

Fat Model, Skinny Controller

Write all the non-response-related logics inside the model with nice and testable methods; and don’t forget to use comments.

You should follow the Ruby on Rails motto i.e. “Fat Model, Skinny Controller”. Because the “skinny” controller offers a nice interface between the view and model.

By moving any logic that isn’t about the response (for example, setting a flash message, or choosing whether to redirect or render a view) to the model instead of the controller, not only you can reuse the codes where

possible but you’ve also made it possible to test your code.

Reusable Scopes

A scope is a set of constraints on database interactions (such as a condition, limit, or offset) that are chainable and reusable.

Let’s see a simple example:

[sourcecode language=”plain”]
def index
@paid_users= User.where(“is_active=? AND is_paid=?”,true, true).order(“name”)
@unpaid_users= User.where(“is_active=? AND is_paid=?”, true, false).order(“name”)
[/sourcecode]

You can change it to this:

[sourcecode language=”plain”]
def index
@paid_users= User.paid.all
@unpaid_users= User.unpaid.all
end[/sourcecode]

Then, you can move the logic to your User model, where it might look like this:

[sourcecode language=”plain”]
scope :paid, lambda { where(“is_active=? AND is_paid=?”,true, true).order(“name”) }
scope :unpaid, lambda { where(“is_active=? AND is_paid=?”,true, false).order(“name”) }
[/sourcecode]

Using the methods User.paid.all and User.unpaid.all, we’ve not only made it simpler to test our code, but also made it possible to reuse that same set of conditions in another location.

You should avoid the use of default_scope because:

  1. You can’t override default scope
  2. default_scope will affect your model initialization

Package Your Code into Gems and Plugins

Writing a particular set code more than once for different applications is exhausting as well as redundant, hence, it is advisable to create a plugin or gem to use it further. It will save your development time and effort.

Manage Your Attribute Access

While creating or updating an object, Rails app usually assigns every attribute without checking the data. Validation only prevents the bad data but doesn’t exactly prevent it from overwriting an attribute that we don’t want to change.

To solve this issue, ActiveRecord is implemented which uses two methods: attr_protected and attr_accessibile.

Using attr_protected, you can declare a blacklist of variables you don’t want to be assigned and using attr_accessible, you can declare a list of variables that can be assigned.

By implementing above steps, you could prevent any mass assignment that could occur via your application’s forms; because if the form does not have the field for a given attribute, doesn’t mean a hacker can’t add it to the request.

From a security perspective, using attr_accessible and attr_protected forces you to think about what should be editable and how to protect the ways in which your class’s attributes are set.

Use Non-database-backed Models

In Rails app, Model is not restricted to associate with table. To organize application logic, write it down by creating a new model.

Virtual Attributes

If you are manipulating data before passing it to a model, use virtual attributes instead.

Virtual attributes are a simple own getter and setter methods.

For example
To set a user’s name:

[sourcecode language=”plain”]
@user = User.new(params[:user])
@user.first_name, @user.last_name = params[:user][:name].split(" ", 2)
[/sourcecode]

By using virtual method inside the model

[sourcecode language=”plain”]
def name=(value)
self.first_name, self.last_name = value.to_s.split(“ ”, 2)
end[/sourcecode]

Whenever you set the name attribute, your model will automatically set the first_name and last_name attributes for you, even though name doesn’t exist in the database.

Use Translations

Rails i18n framework makes it easy to declare the map of an abstract context to a string.

All you need to do is maintain a YAML file of translations, and use I18n.t / t in your code where there is data shown to the use.

I18n is useful to avail your app to more locales.

Using of after_commit callback

Use “after_commit” instead of using after_create/after_update/after_destroy callbacks to start background processes. Because, in relational database, several operations are wrapped in one unit and pass or fail of transaction depends upon all the operations.

If you use after_create/after_update/after_destroy in first model and if any error occurs in the second model then the background process will raise NotFoundError.

Use select in ActiveRecord association

Use select with has_many and belongs_to on Active Record Associations to speed up the query.

For example:

[sourcecode language=”plain”]
class Patient < ActiveRecord::Base
belongs_to :physician, :select => ‘id,name, surname’
end

class Physician < ActiveRecord::Base
has_many :patients, :select => ‘id,name, physician_id’
end
[/sourcecode]

Fix N+1 Queries

N+1 Queries is a serious database performance problem. Use “Bullet” gem to avoid N+1 query problem

Conclusion:

Employing the above mentioned Rails best practices would keep the code cleaner and reusable.

The application performance would increases tremendously and the maintenance of the code will be easier.

Steps to execute pagination using “Kaminari” gem in Rails3

Pagination is a technique that divides content into manageable chunks, allowing users to easily browse through a dataset. 

In this blog, we’ll dive into the process of implementing pagination using the “Kaminari” gem in a Rails 3 application. 

Kaminari is a powerful and flexible gem that simplifies the pagination process, enhancing the performance and usability of your web application.

Key Features:

  • Easy to use.
  • Customizable engine-based I18n-aware helper.
  • The pagination helper outputs the HTML5 <nav> tag by default and the helper supports Rails 3 unobtrusive Ajax.

Recommended Reading: AJAX Pagination using jQuery in Rails3

Here are the steps to implement “kaminari gem” in a Rails app.

Step#1

  • Put this code in your Gemfile:

[sourcecode]gem ‘kaminari'[/sourcecode]

  • Run “bundle install”

Step#2

  • Modify the controller as mentioned below

[sourcecode]@blogs = Blog.order("name").page(params[:page])[/sourcecode]

Step#3

  • Now, add the paginate helper method in your listing page which is provided by Kaminari, by passing in the list we’re paginating.

[sourcecode]<%= paginate @blogs%>[/sourcecode]

Step#4

  • When the page reloads, the pagination links will be visible. Kaminari will show 25 items per page by default, but we can easily change that by calling another scope called “per” as mentioned below.

[sourcecode]@blogs = Blog.order("name").page(params[:page]).per(10)[/sourcecode]

  • Now it should display 10 items per page.

Step#5

  • You can configure the below mentioned default values of kaminari by running the command

[sourcecode]rails g kaminari:config[/sourcecode]

It’ll generate a file “kaminari_config.rb” in your config/initializers folder with the following code snippet as commented.

[sourcecode]
default_per_page # 25 by default
max_per_page # nil by default
window # 4 by default
outer_window # 0 by default
left # 0 by default
right # 0 by default
page_method_name # :page by default
param_name # :page by default[/sourcecode]

  • Next, you can change the values according to your requirement.
  • If you change your view page like:

[sourcecode]<%= paginate @blogs, :window => 2 %> [/sourcecode]

  • The output will be:

[sourcecode]« First ‹ Prev 1 2 3 4 5 … Next › Last »[/sourcecode]

  • There are some other custom attributes you can use in view page like:

[sourcecode]
<%= paginate @users, :outer_window => 3 %>
<%= paginate @users, :left => 1, :right => 3 %>
<%= paginate @users, :params => {:controller => ‘foo’, :action => ‘bar’} %>
<%= paginate @users, :remote => true %> [/sourcecode]

Kaminari also includes a handy template generator. You can override them by running following command.

[sourcecode]rails g kaminari:views default[/sourcecode]

It’ll generate a “Kaminari” folder in app/views with dependent files inside it.

I hope you liked it. If you want you can contact our experienced ruby on rails developer for your webs and mobile application.
Please leave your comment about this post on the comment section below.

Ruby On Rails Releases Fixes For DoS, XSS Vulnerabilities

In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

How To Implement Security Patches On Ruby On Rails Applications

The security of any software product or application is something that every software solution provider is wary of. It is no different in the case of a Ruby on Rails application.

Even after an application is successfully developed and deployed, there can be possibilities for many unseemly activities.

US-based high-end software solution provider Andolasoft.Inc sheds some light on some of the basic precautions that are worked upon before deploying an application.

The Company’s Ruby on Rails developers pay special attention to security issues in every undertaken venture.
Authentication and authorization of the User model are two different things.

Never miss an update from us. Join 10,000+ marketers and leaders.

Actions like create/update/delete always need to be protected. Even popular plug-ins like Restful authentication and Clearance only authenticate whereas providing no helper methods for authorization.

Mass assignment of sensitive attributes from re-assignment should be protected.

This can be taken care of by disabling mass assignment with the help of attr_accessible or attr_protected in the respective models. Attributes like account_id’s and user_id’ should be protected.

Also disabling updates on protected attributes can be by using attr_readonly so that the Ids don’t get updated once set.

Content types of files being uploaded can be faked, so uploaded files should be placed in protected directories or servers.

Also, file extensions should be checked and the web-server should be disabled so as not to execute such files in the uploaded directories.

Sessions are prone to vulnerabilities like hijacks, replaying cookies, and session fixation. Extra caution must be taken regarding storing data in sessions.

Active record Objects should never be stored in sessions which might change that Object’s behavior while migration and future code change.

The best practice is to only store the ids of the records. Also, sensitive data like User access privileges and money based information should not be stored in sessions.

Ruby Rails Development Sphere & Associated Myths

Ruby on Rails development is fast changing the norms of web development across the globe.

Companies around the world are fast catching up with this magical web development framework for exploring and executing its true potentials; thereby serving their clients with really cost-effective, quick and dynamic Ruby on Rails Applications.

Ruby developers and Rails developers are becoming the most sought after skilled professionals, for Software companies to hunt for.

Ruby on Rails, being an Open Source tool, coupled with fast development life cycle, requires much less resources in terms of Programmers and man-hours; which results in the service provider and client being the ultimate beneficiaries.

Silicon Valley based leading Software firm, Andolasoft Inc. is a formidable force to reckon with as far as Ruby on Rails development is concerned.

Never miss an update from us. Join 10,000+ marketers and leaders.

With a vast pool of Programmers as well as Domain Leads, this fairly young Enterprise has carved out many Social Networking Sites, Social Media Marketing web apps.

Andolasoft services include but not limited to RoR Development, RoR Application Migration, Social Media Integration, System Administration, Redesigning of Existing Apps, Performance Improvement Related Tasks and Rescue Support.

Irrespective of all its popularity, RoR also has few myths related to it.

Applications can be built hundreds of thousands times faster than other technologies: The fact is Rails doesn’t write the code automatically.

It just lets the developers work easy by managing certain functionalities; thereby allowing them to focus on other crucial modules.

It also manages the laborious part of lifting of user interactive modules. Having said that, such myths reflects a wrong opinion upon customers, whose expectations sometimes become too high for the service providers.

Even Non-programmers can build web applications: This is by far the silliest perception about Rails development. Although the simplicity of this framework and clean syntax of ruby language assist in quick development, but still experience is required as far as writing code is concerned.

Rails developers do need to write new and unique code, apart from using the Rails conventions on top a comprehensive web development framework.