Starting Ruby on Rails: What I Wish I Knew
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.
- Agile Web Development with Rails. Yes, it’s a book. And a cohesive book is worth 100 hobbled-together online tutorials.
- InstantRails: A .zip file containing Ruby, Apache, MySQL and PHP (for PhpMyAdmin), packaged and ready to go.
- Aptana/RadRails (like Eclipse) or Ruby In Steel (like Visual Studio) for editing code.
- Subversion and/or TortoiseSVN for source control.
- Browse popular ruby on rails links on del.icio.us, Rails documentation and Ruby syntax & examples.
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
returnexplicitly 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 = 3is a local variable for a method or block (gone when the method is done)@x = 3is a instance variable owned by each object (it sticks around)@@x = 3is a class variable shared by all objects (it sticks around, too).:hellois 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
Personto be saved to a database table namedpeople. 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:
- How To Debug Web Applications With Firefox
- How To Optimize Your Site With HTTP Caching
- How To Optimize Your Site With GZIP Compression
- Speed Up Your Javascript Load Time
- The Quick Guide to GUIDs
Until next time, enjoy these amusing videos:
71 Comments »
Trackbacks & Pingbacks
-
Pingback by links for 2007-06-18 « B-link List — June 17, 2007 @ 5:41 pm
-
Pingback by InAnger.com » Blog Archive » Ruby Isn’t It Great! — June 18, 2007 @ 11:50 am
-
Pingback by At the speed of pagination – Bootstrap article on Rails — June 18, 2007 @ 12:16 pm
-
Pingback by error is the mother of all inventions — June 18, 2007 @ 10:40 pm
-
Pingback by Lyhyt johdatus Railsiin by posliini — June 18, 2007 @ 10:57 pm
-
Pingback by Starting Ruby on Rails: What I Wish I Knew at mikehc.com — June 18, 2007 @ 11:13 pm
-
Pingback by Digg IT! » Wanna start the Rails? — June 18, 2007 @ 11:20 pm
-
Pingback by Starting Ruby on Rails: What I Wish I Knew « v1ruz blog — June 18, 2007 @ 11:33 pm
-
Pingback by .:: ju ::. » links for 2007-06-19 — June 19, 2007 @ 1:22 am
-
Trackback by The Bleeding Edge — June 19, 2007 @ 4:31 am
-
Trackback by Techniqal Support — June 19, 2007 @ 7:03 am
-
Pingback by Free as in Time » Blog Archive » RoR Tuesday 19/06/2007 — June 19, 2007 @ 9:08 am
-
Pingback by Starting Ruby on Rails: What I Wish I Knew « GeekStalker — June 19, 2007 @ 9:50 am
-
Pingback by SeoGenetic Blogs » Starting Ruby on Rails: What I Wish I Knew — June 19, 2007 @ 11:14 am
-
Trackback by — June 19, 2007 @ 2:17 pm
-
Pingback by James Governor’s Monkchips » links for 2007-06-19 — June 19, 2007 @ 4:33 pm
-
Pingback by links for 2007-06-21 « Jack The Programmer — June 20, 2007 @ 9:23 pm
-
Pingback by ProjectX Blog » Blog Archive » Links — June 21, 2007 @ 8:39 pm
-
Pingback by Starting Ruby on Rails: What I Wish I Knew : Web Dev Newspaper — June 24, 2007 @ 7:32 am
-
Pingback by tech.twomadgeeks.com » Blog Archive » Starting Ruby on Rails — June 28, 2007 @ 3:36 pm
-
Trackback by Quicklinks — June 29, 2007 @ 4:17 am
-
Pingback by New blog of denise » Blog Archive » Starting Ruby on Rails: What I Wish I Knew | BetterExplained — June 29, 2007 @ 10:48 am
-
Pingback by Rails Tutorials at Shawn Sorichetti — June 30, 2007 @ 11:29 am
-
Pingback by Instacalc Blog » Blog Archive » InstaCalc Podcast — July 3, 2007 @ 7:26 am
-
Pingback by Starting out with Ruby on Rails « IS Department — July 3, 2007 @ 3:24 pm
-
Pingback by Links for the Weekend, 7-7-2007 — July 7, 2007 @ 8:50 am
-
Pingback by links for 2007-07-13 at Jeremy Tai Abbett > Suture — July 16, 2007 @ 11:11 am
-
Pingback by Julian Harris, Social Computing Guy » Starting Ruby on Rails: What I Wish I Knew | BetterExplained — July 18, 2007 @ 3:26 pm
-
Pingback by Intermediate Rails: Understanding Models, Views and Controllers | BetterExplained — August 12, 2007 @ 12:47 am
-
Trackback by Jorge Mir Dot Com — September 29, 2007 @ 2:23 am
-
Pingback by Starting Ruby on Rails: What I Wish I Knew « Programming News — October 10, 2007 @ 9:27 am
-
Pingback by Overheard: Ruby on Rails demystified - Overheard in the Blogosphere — October 20, 2007 @ 5:27 pm
-
Pingback by A Fresh Cup » Blog Archive » Double Shot #62 — December 29, 2007 @ 6:56 am
-
Pingback by testing pingbacks — January 10, 2008 @ 3:51 pm
-
Pingback by Latest Bookmarks on Ma.gnolia.com at Ivan Enviroman — February 10, 2008 @ 1:01 am
-
Pingback by 60 Ruby on Rails Tutorials,Cheatsheets,Forums,Plugins,Podcasts,Ebooks… | Speckyboy - Wordpress and Design — April 20, 2008 @ 2:59 am
-
Pingback by 4 Essential & 7 Optional Ruby on Rails Tutorials « BendTheBlock — July 24, 2008 @ 7:00 am
-
Pingback by Agile web development with Ruby on Rails « Random Chusses… — October 17, 2008 @ 8:30 am
Comments
RSS feed for comments on this post. TrackBack URI
Leave a comment
Have a question? Know an explanation that caused your own a-ha moment? Write about it here.




RSS

excelent “bootstrap article” on ruby and rails! Pretty informative for beginners..
herval — June 17, 2007 @ 5:51 pm
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!
trill — June 17, 2007 @ 7:40 pm
Awesome, glad you are finding it useful. Rails is really fun, but has quirks. I hope I can save people some trouble.
Kalid — June 17, 2007 @ 9:37 pm
Avast find a trojan in “http://my.instacalc.com/”.
Alessandro — June 18, 2007 @ 4:29 am
Hi Alessandro, thanks… there’s a false positive with Avast that I’m working on. Unfortunately some AV companies seem to false positive with JS/Feebs:
http://isc.sans.org/diary.html?storyid=2319&rss
Kalid — June 18, 2007 @ 7:23 am
wonderful article! Thx for this! *respect respect*
Alex — June 18, 2007 @ 8:44 am
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
felix — June 18, 2007 @ 12:59 pm
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
.
Kalid — June 18, 2007 @ 1:21 pm
A VIRUS HAS BEEN DETECTED!
File name: http://my.instacalc.com/instacalc/build508/javascripts/library-internal.js.packed\unp50055261
Malware name: JS:Feebs family
Malware type: Virus/Worm
ju
ju — June 19, 2007 @ 2:23 am
Excellent article for someone starting out on Rails. Great job.
Chad Michel — June 19, 2007 @ 6:36 am
Thanks ju, there was a false positive with Avast that I’ve fixed. I had to split a library file in two, more info here: http://reddit.com/info/1rwjd/comments/c1rz5z
Kalid — June 19, 2007 @ 6:43 am
Thanks Chad, glad you enjoyed it.
Kalid — June 19, 2007 @ 6:43 am
Business logic should be in models! not controllers. Please use the fat model approach, it will save you a lot of hassle.
Ryan T Mulligan — June 19, 2007 @ 3:33 pm
Thanks Ryan, I’ve updated the article with the fat model approach.
Kalid — June 19, 2007 @ 8:41 pm
It appears your link to the HTTP Caching article is actually pointing to the GUID article…
Richard — June 27, 2007 @ 4:36 am
Whoops, thanks for the catch. I just updated the link.
Kalid — June 27, 2007 @ 11:34 am
AWSOME..Very Helpful
Mark Howard — June 28, 2007 @ 5:39 pm
Thanks Mark, glad you liked it.
Kalid — June 29, 2007 @ 8:38 am
I’m just starting learning Ruby and your article is very helpful, thanks !
Somaninn — July 19, 2007 @ 12:55 pm
Glad you liked it — Ruby is really fun once you get into it, good luck.
Kalid — July 20, 2007 @ 7:19 am
:conditions =>[ ” name like ?”, ‘”.params[:keyword].”%’])
what is correct code of this line ?????????
rupali — November 20, 2007 @ 2:18 am
Hi, I think it’s supposed to be like this:
http://railsruby.blogspot.com/2006/08/like-as-condition-to-get-records.html
Kalid — November 20, 2007 @ 12:53 pm
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!
collector — January 22, 2008 @ 10:40 am
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.
Kalid — January 22, 2008 @ 10:53 pm
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!
ChrisR — April 23, 2008 @ 11:46 am
Hi Chris, I would start with Instantrails — it has all the components in a single directory. Good luck!
Kalid — April 23, 2008 @ 12:30 pm
Thanks for the concise and clear articles. I have a small correction for you: YAML stands for “YAML Ain’t a Markup Language” (http://www.yaml.org/).
Keep up the great work!
brookr — May 12, 2008 @ 8:22 am
Hi Brookr, appreciate the info — I just changed the article
.
Kalid — May 12, 2008 @ 8:29 am
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!!!
angieh — May 29, 2008 @ 5:08 am
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
.
Kalid — May 29, 2008 @ 9:11 am
only Thanks
MihanDownload — September 18, 2008 @ 1:51 am