Starting Ruby on Rails: What I Wish I Knew

Get the Math, Better Explained eBook and turn Huh? to Aha!

Ruby on Rails is an elegant, compact and fun way to build web applications. Unfortunately, many gotchas await the new programmer. Now that I have a few rails projects under my belt, here’s my shot at sparing you the suffering I experienced when first getting started.

Tools: Just Get Them

Here’s the tools you’ll need. Don’t read endless reviews trying to decide on the best one; start somewhere and get going.

But What Does It All Mean?

“Ruby on Rails” is catchy but confusing. Is Rails some type of magical drug that Ruby is on? (Depending on who you ask, yes.)

Ruby is a programming language, similar to Python and Perl. It is dynamically typed (no need for “int i”), interpreted, and can be modified at runtime (such as adding new methods to classes). It has dozens of shortcuts that make it very clean; methods are rarely over 10 lines. It has good RegEx support and works well for shell scripting.

Rails is a gem, or a Ruby library. Some gems let you use the Win32 API. Others handle networking. Rails helps make web applications, providing classes for saving to the database, handling URLs and displaying html (along with a webserver, maintenance tasks, a debugging console and much more).

IRB is the interactive Ruby console (type “irb” to use). Rails has a special IRB console to access your web app as it is running (excellent for live debugging).

Rake is Ruby’s version of Make. Define and run maintenance tasks like setting up databases, reloading data, backing up, or even deploying an app to your website.

Erb is embedded Ruby, which is like PHP. It lets you mix Ruby with HTML (for example):

<div>Hello there, <%= get_user_name() %></div>

YAML (or YML) means “YAML Ain’t a Markup Language” — it’s a simple way to specify data:

{name: John Smith, age: 33}

It’s like JSON, much leaner than XML, and used by Rails for setting configuration options (like setting the database name and password).

Phew! Once Ruby is installed and in your path, you can add the rails gem using:

gem install rails

In general, use gem install “gem_name”, which searches online sources for that library. Although Rails is “just another gem”, it is the killer library that brought Ruby into the limelight.

Understanding Ruby-Isms

It’s daunting to learn a new library and a new language at the same time. Here are some of the biggest Ruby gotchas for those with a C/C++/Java background.

Ruby removes unnecessary cruft: (){};

  • Parenthesis on method calls are optional; use print "hi".
  • Semicolons aren’t needed after each line (crazy, I know).
  • Use “if then else end” rather than braces.
  • Parens aren’t needed around the conditions in if-then statements.
  • Methods automatically return the last line (call return explicitly if needed)

Ruby scraps the annoying, ubiquitous punctuation that distracts from the program logic. Why put parens ((around),(everything))? Again, if you want parens, put ‘em in there. But you’ll take off the training wheels soon enough.

The line noise (er, “punctuation”) we use in C and Java is for the compiler’s benefit, not ours. Be warned: after weeks with Ruby, other languages become a bit painful to read.

def greet(name)              # simple method
   "Hello, " + name          # returned automatically
end

greet "world"                # ==> "Hello, world"

Those Funny Ruby Variables

  • x = 3 is a local variable for a method or block (gone when the method is done)
  • @x = 3 is a instance variable owned by each object (it sticks around)
  • @@x = 3 is a class variable shared by all objects (it sticks around, too).
  • :hello is a symbol, like a constant string. Useful for indexing hashes. Speaking of which…
  • dictionary = { :cat => "Goes meow", :dog => "Barks loud."} is a hash of key/value pairs. Access elements with dictionary[:cat].

Those Funny Ruby Assignments

Ruby has the || operator which is a bit funky. When put in a chain

x = a || b || c || "default"

it means “test each value and return the first that’s not false.” So if a is false, it tries b. If b is false, it tries c. Otherwise, it returns the string “default”.

If you write x = x || "default" it means “set x to itself (if it has a value), otherwise use the default.” An easier way to write this is

x ||= "default"

which means the same: set x to the default value unless it has some other value. You’ll see this a lot in Ruby programs.

Those Funny Ruby Blocks

Ruby has “blocks”, which are like anonymous functions passed to a loop or another function. These blocks can specify a parameter using |param| and then take actions, call functions of their own, and so on. Blocks are useful when applying some function to each element of an array. It helps to think of them as a type of anonymous function that can, but doesn’t have to, take a parameter.

3.times do |i|
   print i*i
end

In this example, the numbers 0,1 and 2 are passed to a block (do… end) that takes a single parameter (i) and prints i squared. The output would be 0, followed by 1 followed by 4 (and looks like “014″ since we didn’t include spaces). Blocks are common in Ruby but take some getting used to, so be forewarned.

These are the Ruby lessons that were tricky when starting out. Try Why’s Poignant Guide To Ruby for more info (“Why” is the name of the author… it confused me too).

Understanding Rails-isms

Rails has its own peculiarities. “Trust us, it’s good for you.” say the programmers. It’s true – the features/quirks make Rails stand out, but they’re confusing until they click. Remember:

  • Class and table names are important. Rails has certain naming conventions; it expects objects from the class Person to be saved to a database table named people. Yes, Rails has a pluralization engine to figure out what object maps to what table (I kid you not). This magic is great, but scary at first when you’re not sure how classes and tables are getting linked together.
  • Many methods take an “options” hash as a parameter, rather than having dozens of individual parameters. When you see

    link_to “View Post”, :action => ‘show’, :controller => ‘article’, :id => @article

The call is really doing this:

link_to("View Post", {:action => 'show', :controller => 'article', :id => @article})

There are only two parameters: the name (“View Post”) and a hash with 3 key/value pairs. Ruby lets us remove the extra parens and braces, leaving the stripped-down function call above.

Understanding The Model-View-Controller Pattern

Rails is built around the model-view-controller pattern. It’s a simple concept: separate the data, logic, and display layers of your program. This lets you split functionality cleanly, just like having separate HTML, CSS and Javascript files prevents your code from mushing together. Here’s the MVC breakdown:

  • Models are classes that talk to the databse. You find, create and save models, so you don’t (usually) have to write SQL. Rails has a class to handle the magic of saving to a database when a model is updated.
  • Controllers take user input (like a URL) and decide what to do (show a page, order an item, post a comment). They may initially have business logic, like finding the right models or changing data. As your rails ninjitsu improves, constantly refactor and move business logic into the model (fat model, skinny controller). Ideally, controllers just take inputs, call model methods, and pass outputs to the view (including error messages).
  • Views display the output, usually HTML. They use ERB and this part of Rails is like PHP - you use HTML templates with some Ruby variables thrown in. Rails also makes it easy to create views as XML (for web services/RSS feeds) or JSON (for AJAX calls).

The MVC pattern is key to building a readable, maintainable and easily-updateable web app.

Understanding Rails’ Directory Structure

When you create your first rails app, the directories are laid out for you. The structure is well-organized: Models are in app/models, controllers in app/controllers, and views in app/my_local_views (just kidding).

The naming conventions are important – it lets rails applications “find their parts” easily, without additional configuration. Also, it’s very easy for another programmer to understand and learn from any rails app. I can take a look at Typo, the rails blogging software, and have a good idea of how it works in minutes. Consistency creates comprehension.

Understanding Rails’ Scaffolding

Scaffolding gives you default controller actions (URLs to visit) and a view (forms to fill out) to interact with your data — you don’t need to build an interface yourself. You do need to define the Model and create a database table.

Think of scaffolds as the “default” interface you can use to interact with your app – you’ll slowly override parts of the default as your app is built. You specify scaffolds in the controller with a single line:

scaffold :person

and it adds default actions and views for showing, editing, and creating your “Person” object. Rails forms take some getting used to, so scaffolding helps a lot in the initial stages.

More Tips and Tricks

I originally planned on a list of tips & tricks I found helpful when learning rails. It quickly struck me that Ruby on Rails actually requires a lot of background knowledge, and despite (or because of) its “magic”, it can still be confusing. I’ll get into my favorite tricks in an upcoming article.

As you dive further into web development, these guides may be helpful:

Until next time, enjoy these amusing videos:

Other Posts In This Series

  1. Starting Ruby on Rails: What I Wish I Knew
  2. Intermediate Rails: Understanding Models, Views and Controllers
  3. A Simple, Comprehensive Overview of Javascript
  4. Using JSON to Exchange Data
  5. How To Make a Bookmarklet For Your Web Application
Kalid Azad loves sharing Aha! moments. BetterExplained is dedicated to learning with intuition, not memorization, and is honored to serve 250k readers monthly.

Enjoy this article? Try the site guide or join the newsletter:
Math, Better Explained is a highly-regarded Amazon bestseller. This 12-part book explains math essentials in a friendly, intuitive manner.

"If 6 stars were an option I'd give 6 stars." -- read more reviews

55 Comments

  1. Very good article. I’m new to Rails and articles like these keep me motivated. I’ll be checking your blog for my tips! Thx!

  2. Awesome, glad you are finding it useful. Rails is really fun, but has quirks. I hope I can save people some trouble.

  3. thanks.
    the most annoying thing about rails is all the tutorials that say “gosh ! its so easy ! look I’m already done !” and fail to actually give us any useful details.
    you were all meat :)

  4. Thanks Felix. I’m glad you liked it, I find it annoying when tutorials don’t actually give examples, so I’m happy that came through :).

  5. It appears your link to the HTTP Caching article is actually pointing to the GUID article…

  6. Kalid, as i understand the server where web application is going to be hosted has to have Ruby installed? If so, it does not look like many hosting companies have it installed.
    Excellent article by the way. Spent few hours on your site, and learned more than a month browsing elsewhere. Thank you!

  7. Thanks, I’m glad you’re finding the site helpful! You got it — Ruby needs to be installed to run the various files (with a .rb extension).

    Unfortunately, Ruby is not as popular as other languages (like Perl, Java or PHP) and may not be installed by default. Some hosting companies pride themselves in being “Rails ready”, which you may have to ask for if on a shared server.

  8. Hi,

    I’ve had SO much hassle trying to install RoR…I’m an amateur (i.e. newbie) trying to learn what I keep reading is an Agile tool. However, I can’t find a decent packaged installation, which includes everything I need. I’ve now got about 5 different versions of RoR, which I fear maybe adding to my problems.

    Any help appreciated!

  9. Hi Chris, I would start with Instantrails — it has all the components in a single directory. Good luck!

  10. I really appreciate this article. I have spent a few days and lots of Tylenol trying to get it going. Luckily, I’m working with someone who is having much more luck than me, but I have a lot of studying to do. I bookmarked your site and look forward to reading more.

    I just wish I found your site in the beginning! Great writing, easy to read, and concise. THANKS!!!

  11. Thanks angieh, glad it’s coming in useful (and happy you’re enjoying the site)! Yes, Rails is nice but has a lot of trial-and-error — good luck with your project :).

  12. I just came across your site -> Wonderful advice and seeing this makes me feel great as I have tackled many of these issues before actually learning Rails.

    It is so useful for a newcomer to actually go about and find useful info and read what others say before getting their hands dirty..

    One other thing i find very cool lately is the Ruby console: ruby script/console – In Windows ;-) This way you can check for errors, find, sort add stuff in your database.

    A cool tool for an inspiring “someone”!!!

    Oh about Instant Rails => Great little tool, but my opinion is going the manual way with the sql adapter(on windows). Easy as pie to install (first install ruby) then:

    > gem install rails capistrano mysql mongrel mongrel_cluster

  13. @Ahad: Thanks for the comment! Really glad you enjoyed the article, it was fun writing about how to overcome the initial roadblock.

    I agree about the console — it’s one of my favorite parts of rails. Debugging web apps can be such a pain, and the console makes it a snap to poke around the live running site.

    Re: instantrails, I still think the single .zip file is easier (just extract and go) but the real setup is more useful for a production server (probably on some Linux distro).

  14. Excellent write-up! I actually started off with RoR and then pretty much gave up and was looking into CI lately. Wasn’t getting satisfied with the spaghetti code structure and just started thinking about getting back to RoR, and this article came right on time. Thanks for the points well touched.

  15. thanks, read this while doing ruby on rails training on lynda.com, this was a nice summary of the basics, thanks!

  16. hi

    great tips!

    but why don’t you remove ALL line-noise in your example of ruby without line-noise?

    def greet name

    is less noisy than

    def greet(name)

    cheers!

  17. Good work, though if you’re recommending Agile Web Development with Rails (as you should) you should also recommend GIT for source control as its now incorporated into the text. Just my two cents. Thanks again!

  18. Excellent overview. The author seems to have solid grasp on what is important to nubes who have some experience in comparable technology.
    Pleaase continue educating the masses. I like the phrase “Consistency creates comprehension” You bet
    - bachi

  19. A tip for people arriving here in 2012 and starting on Windows: install http://railsinstaller.org/ instead of InstantRails. This is now definitely the easiest way to get started with Rails. You get Ruby, Rails, SQLite and Git pre-installed.

    Definitely also start with Git instead of SVN, as it is now the default choice for version control in the Ruby/Rails world.

  20. I am very glad to know about your post which is so informative about ruby on rails. I am looking to learn about ruby programming and your post is very useful in this case.

  21. Full disclosure I run the website I am about to post about:

    Some buddies and I who all work as full time programmers, believe that sometimes we make getting started in programming to hard. We compiled a list of tutorial videos and are growing. If you are looking for help with Ruby check out the video tutorials and let us know what you think.

    http://www.dotprogramming.com/category/ruby/

  22. I wish I hadn’t spent so much time getting STUCK, and trying to figure out basic stuff.

    I wish I had known about CodeJinn.com where I can get exactly the help I need in 15 minutes when I get stuck.

    No struggling for hours, and no paying tens of thousands of dollars for a code school.

Your feedback is welcome -- leave a reply!

Your email address will not be published.

LaTeX: $$e=mc^2$$