Try Tuts+ Premium, Get Cash Back!
Why Rails?

Why Rails?

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 15 Minutes

Your choice, when learning a new framework, is an incredibly important one. It takes countless hours and effort to become proficient and learn all the best practices – even for experienced developers.

That's why it's necessary to understand the peculiarities of a framework as early as possible, in order to determine if it's the right solution for the problem that you’re trying to solve. In this article, I’ll cover many of the key areas of the Ruby on Rails framework, and why I feel that it’s an excellent choice for web developers.


Some History

Ruby on Rails was extracted from the project management application, Basecamp.

Ruby on Rails was open-sourced in 2004, by David Heinemeier Hannson, after being extracted from the project management application, Basecamp.

It's based on the Ruby programming language, and the current stable release is 3.2 – with 4.0 just around the corner!

RoR is a full web application stack; starting with version 3.1, it also includes facilities and libraries to manage frontend code, supporting Sass and CoffeeScript out of the box, with no need for external tool to manage the compile process. Opinionated workflow is the name of the game with Rails.

For development, it embeds its own web server, so that you don't need to install extra software apart from a working Ruby installation.


Why Learn It?

There are countless reasons for learning Rails, ranging from technical to business and productivity. We'll tackle each one by one.

Technology

Ruby has been designed to be a "joy to use".

As its name implies, Rails is based on the Ruby language. Invented in 1993 and released for the first time in 1995 by Yukihiro Matsumoto (widely known simply as "Matz"), Ruby is an object-oriented interpreted language that features a syntax heavily inspired by Perl and Lisp. Since its inception, Ruby has been designed to be a "joy to use" – meaning a strong focus on readability and elegance.

Being a higher level language, Ruby is extremely powerful and versatile, while maintaining a good balance of clarity and performance (bearing in mind that it's still an interpreted, dynamic language).

The original Ruby interpreter (Matz's Ruby Interpreter, shortened as MRI) is written in C, but it's not the only one available nowadays (a couple of notable alternatives are JRuby, running on top of the JVM, and Rubinius).

Ruby features several libraries shipped with its core, including a very powerful unit testing one, called Minitest (prior to Ruby 1.9, Ruby used TestUnit).

Rails is a popular way to get involved with Ruby, so it's not rare nowadays to find people (including myself) whose first introduction to Ruby was through Rails.

Learn the fundamentals of Ruby with Tuts+ Premium.

Structure

Rails is strongly opinionated, when it comes to architectural decisions

Rails is a database-agnostic MVC framework that chooses convention over configuration, which means that it's strongly opinionated, when it comes to architectural decisions, naming conventions, paths and patterns.

In more detail:

  • MVC means that it follows the Model-View-Controller paradigm, so that you can clearly separate concerns when developing an application. This allows your core business logic to be in a single place, avoiding duplication and assisting with maintenance.

  • It follows a RESTful, resource-oriented approach, meaning that it encourages you to think about your business logic from the data standpoint, exposing resources to endpoints that perform CRUD actions. For example, logging into a site can be seen as 'creating a session'; logging out as 'destroying a session'. This approach takes some getting used to, but once you’ve adopted that mindset, it helps in keeping your interfaces consistent and predictable by other developers. Rails applications tend to revolve around models, which manages data persistence.

  • It uses Bundler as a dependency management tool, leveraging the power of the Rubygems community. This ensures a consistent approach for adding third party functionality to an application, with an explicit format that details which libraries we need, and which versions, including resolving nested dependencies.

  • It can support a wide range of databases, with SQLite as a default (good for development) and MysQL and PostgreSQL as first choices for production. MongoDB can also be integrated with minimal effort.

  • Convention means that naming, paths and patterns are usually predictable and shared among fellow Rails developers. This ensures an easier learning curve, focused on the business logic for the app, easier maintenance and less documentation.

  • It's easy to test, with tools that integrate with the framework for unit testing and integration (with JavaScript support) as well. Additionally, the Ruby community, itself, strongly advocates test-driven development, so a good Rails developer is likely quite experienced in testing.

  • A Rails application can be easily deployed to cloud infrastructures, like Heroku, or straight to private servers (it runs great on Ubuntu Linux, for example).

Core Features

Here's a basic rundown of what Rails can do out of the box, along with some code examples. Please note that, even if you’ve never worked with Rails before or even don't know Ruby, this should not prevent you from understanding them, as they are quite readable.

  • Support for data model definition through migrations, i.e. repeatable and reversible database agnostic instructions, which manipulate the database structure. Consider the following migration:

    class CreateEvents < ActiveRecord::Migration
      def change             
        create_table :events do |t|
          t.string :title
          t.date :start_date
          t.date :end_date
          t.boolean :live, :default => false
          t.timestamps
        end
      end
    end
    

    This migration creates an events table, with some basic data, like a title, and uses specific data types that are mapped to specific column types in the underlying database. For example, by default, string uses a VARCHAR(255) column, if using MySQL. This migration can be written manually from scratch, or generated from the command line and then edited before being run.

  • Database agnostic model interface for CRUD actions. Here’s a few examples, given a News model:

    news = News.new(title: 'Sample news')
    # => returns a news instance, not saved to the database
    news.save
    # => runs an insert query and updates the instance with the returned id from the database
    news.title = 'Updated sample news'
    # => sets the title to the new value, without saving to the database
    news.save
    # => runs an update query for that item
    news.destroy
    # => runs a delete query for that item
    

    In addition, Rails provides a simple interface to perform selection queries, including joins between models.

    News.where(published: true).order('created_at DESC').limit(5)
    # => produces 'SELECT * from news where published = 1 order by created_at DESC limit 5'
    
  • Support for validations; an Event model may always require the presence of a unique title. In that case, it's possible to clearly express these requirements in the Event class:

    class Event < ActiveRecord::Base
    
      validates :title, :presence => true, :uniqueness => true
    
    end
    

    This functionality ensures that no invalid record is saved to the database, and also provides all the bindings needed to display validation errors to the user (for example in a form).

  • Session and cookies with simple helpers to set values, get and delete them, with transparent signature.

  • Protection against form forgery, so that any form you generate through Rails is automatically signed with a token that guarantees its genuinely.

  • Aggressive XSS protection policy enabled by default, so that any form element you use is protected by default, unless you explicitly whitelist it (careful when doing that!).

  • Simple management for GET and POST data, accessible through a simple hash available in every controller action.

  • Simple bindings to connect controllers, models and views, with clear and conventional rules that simplify file management and code. For example, consider the following controller that is responsible for rendering a news list page at http://example.com/news:

    class NewsController < ApplicationController
    
        def index
    
        end
    
    end
    

    Even without writing any code to define what index does, Rails provides a default behaviour, which is to render the app/views/news/index.html.erb view. This reduces the need for boilerplate code, as, most of the time, it's just necessary to override behavior, when unconventional.

  • Integration with external services; Rails offers a rich ecosystem of applications that you can use to monitor, maintain and improve your application (some of them work with other frameworks as well). New Relic helps in monitoring performance, Airbrake collects exceptions to notify the development team, Code Climate analyzes your codebase for quality, complexity and duplication, Tddium and TravisCI can run your test suite remotely against different Ruby versions.

  • As noted previously, Rails also offers an integrated environment to work with Coffeescript and Sass, with transparent compilation in development and preprocessing and cache busting for deployment, so that your production app will serve single, minified files with a signature in the filename. This way, you can be absolutely sure that any browser will always load and cache the latest version of the file.


Business Value

Have you ever wondered why Rails is the first choice of many web startups? There are two primary reasons:

  • It lets you work on features with minimal boilerplate, removing a lot of non-business related work from the development process. This translates into increased velocity in developing and deploying new features, which is key to understanding if the product is solid.

  • Rails’ structure makes it easy to accommodate change. This is certainly true for many MVC frameworks, though Rails is particularly good at restructuring your application flow, reusing components in a simple way.

It's important to remember that, frequently, development time is more costly than an extra server.

There's always an ongoing conversation about Rails performance, and how it can become a bottleneck when you get thousands of hits a minute. The problem is that getting to that level of traffic requires a huge effort. The truth is: 9 times out of 10, scalability is a problem that many companies never need to face. To them, the ability to make changes, easy maintainability and predictability are far more valuable.

In addition, it's important to remember that, frequently, development time is more costly than an extra server. A framework like Rails is often preferred, because, even if it may need more powerful hardware, it’s still cost effective in other areas.

This doesn't mean that you shouldn't care about the performance of your code or worry about topics, such as caching and query optimization. Instead, it means taking into account the full spectrum of hardware and software changes you can make; sometimes, it's sensible to pospone a performance focused chunk of work and temporarily have more powerful hardware to continue working on important features.


Extending the Framework

Rails can easily be extended with a wide variety of external libraries, distributed through Rubygems. Most of the times, any feature that you need to build is already offered through a gem. Now, this doesn't mean that adding gems is the perfect solution; every third party dependency that you add to an application becomes a risk factor.

Sometimes, it's preferable to roll your own version with custom code.

That said, you shouldn't reinvent the wheel. Many Rails applications use the same gems to provide specific features; this can be seen as an advantage. Remember: wide usage translates to wide testing, so it's considered a safe practice to use certain well known gems to accomplish key tasks. Here are a few examples:

This list could easily go on, but the point is that Rails leverages the modularity of a Rubygems-based approach and can greatly speed up development, by placing focus on building features that matter for the product you're working on, instead of boilerplate.


Why I Enjoy Working With Rails

I can focus on what matters for clients without compromising on good code quality.

Roughly two years ago, I was working in a marketing/product management role (doing web development as a hobby); that meant focusing on product features, their business value and the cost associated with their development. When I decided to switch careers, Rails 3.0 had just been released. I spent an afternoon watching videos and reading tutorials. I quickly decided that Rails was what I wanted to focus my efforts on.

The reason – and this somewhat overlaps with what we’ve already discussed – is that I could see a practical approach in the framemork, a clear goal to be productive and focus on the product and its development. I could get things done in a short amount of time. After a few months of intensive self-training through various web tutorials and some sample applications, I applied for my current job as a Rails developer at New Bamboo.

I enjoy working with Rails every day, because I can focus on what matters for clients without compromising on good code quality. To me, it's the perfect starting point for most web-based applications.

It doesn't solve all the problems you’ll encounter, when building large web applications. There are times when you clearly see that Rails isn't fit for a specific kind of service, but that's the time to split the architecture into smaller applications.


Conclusion

Rails is a powerful framework that can help you become more productive and confident, when working on complex projects. This is possible, thanks to its strong conventions and solid structure. Large companies, such as 37 Signals, Pivotal Labs, Groupon (or even Twitter in the old days) have chosen Rails as the base architecture for their core applications. There’s a reason why!

Ready to start Riding Ruby on Rails?

Tags: rails
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://twitter.com/chazzerguy Chaz Hinkle

    I was first introduced to RoR five years ago and built my first Rails site shortly thereafter. I was CONVINCED that Ruby on Rails was the next big thing. Now, five years later, I’m no longer convinced. Sure there are plenty of folks out there developing it, but to me it feels like it never caught fire the way it should have. Too bad really. I enjoy coding in it.

    • pixelBender67

      I just started messing around with it and love it, same as you I can’t believe it’s not more popular..
      things that make you go huh?

      • http://danharper.me/ Dan Harper

        I don’t think RoR could be any more popular. It doesn’t get a huge amount of coverage on Nettuts+, but the community is huge.

      • pixelBender67

        It’s not as popular as PHP or Python

      • Bilal

        It’s not really necessary that’s why. Easier to code your own in procedural or create/use your own functions or classes. That gives you a lot more power over what you do.

      • jeff_way

        Couldn’t disagree with this statement more.

      • http://www.martin-brennan.com/ Martin Brennan

        It does give you a lot more power and control but it also takes much, much longer than using an already established framework. 9/10 times there is no need to reinvent the wheel.

      • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

        What if you think to have a better wheel, don’t you think is the reason why so many developers make their own frameworks ? :)

      • http://www.martin-brennan.com/ Martin Brennan

        Nothing wrong with that, but If you think of a better wheel, best to make it as a separate project rather than making a new wheel for each project.

      • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

        Well, it wouldn’t make any sense to do that.

      • Andy

        Sorry but you’re so wrong. Unless you code your site in assembler then you are being hypocritical. If you do development as a hobby: Sure rewrite the same thing over and over, but when you are developing for a living, you can’t afford to spend months building stuff from scratch for no real reason other than bragging rights. Rails is awesome and when you use it, you’ll see why.

    • igotrailed

      I read lots about new web startups (from techcrunch and other web events website..), and I use buitwith firefox plugin to check which framework a web app is built with and most of the time I find RoR used. I think RoR did catch fire.

    • ppasindu

      I think one problem is hosting there is almost no free hosting spaces except for few.

    • http://terriblelabs.com Jeremy Weiskotten

      If you enjoy coding in it, and it solves problems for you, who cares? FWIW I think Rails has caught fire, especially in startups, and it’s being used more and more in bigger companies.

  • http://michieldemey.be/ Michiel De Mey

    I’m currently developing in Rails 3 and I can really say that it’s been a joy so far.
    However, there are oddities when using Rails and these can lead to a negative experience.

    But I’ve used quite a few frameworks (mainly PHP) and I can say that Ruby on Rails really delivers. And I will probably continue to use Rails in the future.

  • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

    I am not conviced, i stick with php and its frameworks since they are more easy to setup and deploy (in my country atleast), also better to put my time try something more exciting like js/nodejs.

    • http://terriblelabs.com Jeremy Weiskotten

      The current PHP frameworks were inspired by, heavily borrow from, and lag behind Rails.

    • Andy

      It’s actually the opposite when you get to grips with rails. PHP Frameworks (Code Igniter, Cake etc) all are based on Rails. PHP being the horrible language it is, is never going to be able to match the ease of Rails tbh.

  • Mr.Nobody

    Looks like RoR is no longer the mainstream. Nodejs is the new king and thanks God, PHP and Python are quite the same popular as 5 years ago.

  • David D’hont

    Ugh, I give up, I officially now have lost all hope in NetTuts.

    If you don’t see it you deserve it.

    • Claudio Ortolina

      Author here. Can you please explain what you mean? Thanks.

      • David D’hont

        Spent 30 minutes (re)writing explain reply, decided it’s not worth my time. I’m sure you’ll get it some day.

      • Michael Brandt

        What an arrogant reply, deceided it’s not worth your time?
        Why don’t you be constructive, not only for the author’s sake, but for everyone elses as well. You don’t have any credibility when you don’t back up anything you say, other than “it’s not worth my time” Get over yourself.

      • David D’hont

        My initial Criticism was NOT feedback, it was more of a claim that this was the last drop for me when it comes down to NetTuts. And isn’t really anything the Author himself should worry about, other then recognizing that NetTuts does have flaws. (you’d be oblivious to say otherwise).

        I like providing feedback for the greater good. But not for a Website that has Reviewers, Revenue, a simple platform, and yet seems to still ignore free feedback. It so happens I just spent about 3 hours cutting these replies up into proper replies that made sense after the hours had passed, while the rest of you people were too busy calling me Selfish.

        It’s true, I am Arrogant and Selfish. Every person is in a way Selfish, I saw that these debates and feedback I often provide leads me to bigger debates in which I find no joy, I often get hate which is (sometimes) unjustified.

        But time does hold value, based on the things you do with it. And since many of my feedback never gets used anyway, what’s the harm in me exploring the things I could do with that time instead?

        I DO NOT consider myself (or my time) worth more then any of yours. But I do think that my time is worth spent better somewhere else. And that Is a decision I can make. No matter how selfish it is.

      • Omar Naveed

        I love to eat potatoes, David want some?

      • http://www.facebook.com/johan.andre1 Johan André

        You know you act like kindof an jerk? Rails or not, you should respect the work of the author. You can disagree with the opinions posted, but please be constructive…

      • David D’hont

        It was never my intend to disrespect the author’s work. And I do not have an opinion on the matters posted at hand. Because I know very little of Rails, apart from what I read here and on the Rails homepage.

        My problem is with the Context that NetTuts has provided this Article and the content it continues to provide. I do not have any obligation to be constructive to the Author. And my initial reply was not aimed towards the Author (see my edit, above).

      • Claudio Ortolina

        I’ll wait for enlightenment then, thanks for your time.

      • David D’hont

        Such a funny guy you are, this cracked me up, really… Anyway, my previous reply wasn’t meant to be hurtful in any way. I just want you to know that.

      • viczam

        troll alert! Ignore him…

      • jeff_way

        Nettuts+ offers a variety of different content types, including editorials. I think this article absolutely has a place on the site.

      • David D’hont

        Like I said, It’s not up to me to decide the direction for NetTuts to go in. And I know of these categories existing (editorials, etc) and almost never being used. NetTuts and Envato has come a long way. And perhaps is finally starting to move forward. That’s fine. But many of the recent content simply don’t appeal to me any more. Which is why I said that I personally am unsubscribing from some of the feeds, not all of them (premium & marketplaces are something else entirely).

        I know that there is not much I can do about it. But just know that I am not the only one who feels this way. Perhaps something to keep in mind? Just on my Initial post I got 5 likes, and all it said was “I lost all hope in NetTuts”. That actually surprised me.

        By the way, can I just say, the new Style for NetTuts: that however, is truly amazing.

      • srigi

        I must agree with you. Lots of articles here recently contains nothing relevant to site topic (TUTS), but there are always link to TUTS+ premium course. I’m feeling constant shift from good-old net.tuts full of free tutorials into fancy cool magazine acting as frontend for tuts+ premium.

      • David D’hont

        It is of course well within their right to add what is relevant to the site. And mix-match it with the premium courses. It would be a bad idea not to. But yes, the shift is pushing away some users. Like me :)

    • http://twitter.com/rerrify Terry Rosen

      Comments like this are what ruins sites like NetTuts. If you’re too cool for a beginner’s helper article then don’t read it.

      • David D’hont

        You have no idea how much I regret making comments. Not just here, but everywhere. Everytime I do, it turns into a complete mess, it always backlashes, and it seems there to only hold disadvantages.

        I know that I have learned things, about myself. I can’t undo the past… but I can certainly not repeat it.

        By the way, your reply helped me identify the problem that I (just me) have with NetTuts (emphasis on I). Just would like to say thanks for that. You just helped me become a little be more enlightened. I’m not saying this to be Egoistic either. I feel that I’m going to get shit for explaining it so I will not.

        I’m sure the rest of the world (everone else) will want to change when it is ready for it. And I will try only to suggest; rather then dictate or demand.

  • http://www.facebook.com/vusi.bennoah Vusi Ben Noah

    Have been developing in Rails for a year+. I am loving every bit of it. From the development to reasonable hosting cost.

  • Anonmouse

    Good article, even though the web doesn’t need any more “Why Rails” posts. But, 2012 (almost 2013) is not the time to try and convince someone to use a framework that initially released in 2004. And don’t even try and say it has matured, because every release was a deprecate and rewrite everything release. I loved Rails like many developers did because it was a hype language a few years ago. But rather invest your time in JS and NodeJS.

    • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

      Exactly what i am saying..

    • http://www.facebook.com/johan.andre1 Johan André

      I think you should never bet on one framework/language when building for the web. Sure NodeJS and Javascript is cool, for some type of scenarios. There may be times when Rails is the best fit, or Codeigniter, or Python… Or even ASP.NET. (probably not, but why not…)

    • Claudio Ortolina

      I think investing in JS and Node can be rewarding and there’s definitely market for that, but let me point out that:
      - we often forget there’s need for maintenance, so knowing a framerwork used in the last 5+ years has value in that respect.
      - the same way I would not use Rails for certain kinds of services, I would not use not to build a good chunk of features for a large application (user management, login system, plain CRUD). Node can of course do all of this, but this doesn’t mean that it would be the best choice.
      - I wouldn’t choose a language/framework due to hype, rather for what I want to accomplish.

    • http://terriblelabs.com Jeremy Weiskotten

      “And don’t even try and say it has matured, because every release was a deprecate and rewrite everything release.” This isn’t true at all.

  • http://twitter.com/ryanhaywood Ryan Haywood

    What I love about Rails is that it forces you to learn how to be a good software developer. For newer devs getting serious about application development, Rails provides the training wheels necessary to understand good development techniques e.g. Test Driven Development, Model View Controller pattern, REST. Rails also has a huge amount of resources for learning, mainly in RailsCasts.com . When I was starting out, I would get feature requests and then have to hunt on how to do it. RailsCasts had a video showing how to solve my specific problem almost every time.

    Training wheels isn’t a knock though, it’s just a side-effect of the framework being so productive. But for me, Rails was the gateway into a previously daunting and scary world, and when I am developing something in Node I have the foundations of Rails ( good development practices ) backing me up. There isn’t anything else like Rails in the broader (eco system) sense.

    • http://www.facebook.com/people/George-Ulmer/550018154 George Ulmer

      I agree with this. It is one of the few sensible comments on this article.

  • getmetorajesh

    NICE ONE

  • http://www.famesbond.com/ aditya menon

    Cool article to read, I’ll check out Rails sometime, especially for the unit testing knowledge. About the other comments… I guess ‘community’ and ‘hate’ are two words that go hand in hand.

  • Isaac Wardle

    A great and informative article. Rails for me is by far the best framework for rapid development.

  • http://www.martin-brennan.com/ Martin Brennan

    I’ve only just started using Rails on a small app and I’m loving it so far. It seems really easy to get everything going without having to code all your own data access, which is what I currently have to do with ASP.NET webforms. Time will tell though if it turns out to be really great for what I want to do; I might still have to try making a node.js app to see what it’s like too.

  • Kevin Sheppard

    I honestly gave Rails a try and even brought a product to completion with it but I have to say that it left an awful taste in my mouth. There were far too many restrictive conventions and gotchas that made developing a nerve racking experience.

    Coming from a plain PHP and Java EE background, I was intrigues by how simple and sweet the syntax is and how database operations were so heavily abstracted that you can achieve with one line of Ruby what took you 15-20 lines of Java. Beyond that though, everything else – changing to production environment, deploying to a VPS, performing very complex database queries etc. – was so painful!

    I’m much happier in the land of the Play! Framework and I wish it will get some more coverage on Nettuts.

  • http://www.clippingpathcenter.com/clipping-path-service.php mamun

    good design ! Nice job ! I like your post .

  • maurospage

    I really like the structure ror uses and his mvc pattern. I really would like to see some nodejs framework with the same structure. I know, there are railwayjs and locomotive. But they seems a bit “dirty”

  • bgbs

    Not enough years for me to learn a new language. There is pros and cons to everything, but if you stick with one language and learn it well you can get around the cons easily.

    As in languages, in CMS world the same disputes go on. WP vs. Some other choice. I learned to stick with Worpdress I know it well enough that I can go around some of the annoyances that can be easily fixed by going with a different CMS. The only problem is always the learning curve envolved by going with a different thing. We work only 60 years of our life, just not enough time to tinker with this and that, after a certain period in your life, you choose the direction and go with it all the way. The new kids on the block can learn all they want.