Try Tuts+ Premium, Get Cash Back!
Ruby on Rails Techniques

10 Awesome Ruby on Rails Techniques to Get You Started

Rails has seemingly set the web development world on fire these past few years. Popular web applications like Basecamp and Twitter have pushed Rails into the limelight as an excellent framework that any programmer (or even non-programmer) can quickly use to create applications.

One of the most popular aspects of Rails is how easy and intuitive it is to start using right out of the box. Here are 10 tips that beginners can use to help with getting started with the powerful framework.

1. Utilize Source Annotations

If you’re a beginning programmer, you’ll soon realize that a major part of writing code is correctly writing source annotations and comments. While this tip isn’t necessarily Rails specific, it sure does pertain to solid rails coding. If you’re going to annotate your code, use these aptly named keywords:

  • TODO – Used to show code that is incomplete or needs some work
  • FIXME – Used to show code that is broken or buggy
  • OPTIMIZE – Used where further optimizations need to be done

Using these function while programming Rails is especially helpful as Rails allows for adding rake tasks that help you search the code for all the occurrences and prints them out with the file name, line number, and the description.

rake notes
app/controllers/contacts_controller.rb:
  * [ 3] [TODO] factor out model verification to a filter
  * [ 4] [OPTIMIZE] optimize this
  * [ 5] [FIXME] it's broken

Perfect for finding those little things that need some TLC within your code.

2. Monitor Your Apps!

As your Rails applications start to become more complex, you’ll start to notice that some processes might need a tad more TLC in terms of optimization. In order to find those little bugs and errors in your code, try using the excellent Relic RPM to monitor your applications. Relic RPM gives you a chance to monitor all of the processes of your application, and gives you visual graphs and other helpful information to really get a handle on the processes that are causing slowness in your app.

The RailsTips blog has an excellent review of Relic RPM. Analytics are indispensable for developing successful and efficient Rails applications.


Photo by helmet13

3. Group Operations in a Transaction

ActiveRecord is the handy persistence engine that allows you to do many cool things with data and logic. One of the really handy things that ActiveRecord allows you to do is to group multiple inserts in a single transaction. Zen and the Art of Computing gives an excellent example of this technique.

Instead of:

 my_collection.each do |q|
   Quote.create({:phrase => q})
 end

Use:

Quote.transaction do
 my_collection.each do |q|
   Quote.create({:phrase => q})
 end
end

or for rolling back the whole transaction if any insert fails, use:

Quote.transaction do
 my_collection.each do |q|
   quote = Quote.new({:phrase => q})
   quote.save!
 end
end

Photo by Wonderlane

4. Sift Through Page Elements with RJS

One of the incredibly useful aspects of Rails is the built-in support for Javascript and AJAX integrations. They even include a templating language for Javascript called RJS templates. RJS allows the programmer to easily update multiple elements of the page with AJAX.

To take the example a step further, you can use RJS to iterate through page elements and dynamically change them using AJAX. You can even change the elements on the page through CSS queries. For example, you could do something like:

	page.select('#cssid li').each { |item| item.hide }

Nifty, eh? Sifting through the elements can be incredibly powerful to use inside your application’s interface.


Photo by Phillip Ritz

5. Cache Unchanging Data at Application Startup

Performance may not be a huge issue in the development stages of learning Rails, but eventually you’ll want to reach a point where your app is running quickly and smoothly. Caching is an excellent way to speed up an application. RubyInside has an excellent tip on how to cache data that isn’t changed often.

“If you have data that doesn’t change between application restarts, cache it in a constant somewhere. For example, you might have a YAML or XML file in /config that stores application configuration data, and you could load it into a constant in environment.rb, making lookups quick and easy application-wide.”


Photo by flydime

6. Practice to Become a Rails Ninja

While it’s easy to get started with Rails, it takes work to become a pro. Many times beginning programmers believe that frameworks like Rails take out that learning curve, allowing them to quickly become experts. It never works that way. The Framework is only a tool to help you overcome many of the repetitive tasks associated with Ruby.

Jay Fields knows that mastering Rails isn’t easy. In fact he goes on to say the following:

“The screencasts and pictures don’t lie. It is easy to learn Rails and quickly become productive. However, the dirty little secret is that it’s very hard to be come an expert at utilizing Rails.

“Rails provides many helpers that make your life easy. But, you can’t entirely hide the fact that you’ll need to be proficient with Ruby, JavaScript, YAML, and SQL. Just like Rails, getting started with any of the above languages is easy, it’s mastering them that takes time and effort.

“You should always remember that the biggest aspect of becoming an expert is time and practice. Rails is a great framework, but it can only help you so far without doing any extra learning.”

7. Move JavaScript to the Bottom

This is actually a great rule of thumb for just about any language, and it’s good to remember if you’re just getting started with Rails as well. Moving the Javascript includes to the bottom of the template (right before the tag) allows all the HTML to be rendered, so the Javascript doesn’t slow the visual loading of the page.

It’s a simple tip, but it can make a big difference.


Photo by visualpanic

8. Watch Your Form’s Attributes

Forms are a major part of web development, with nearly every web application relying on forms for collecting user information, signups, and a myriad of other uses. However, sometimes new programmer don’t always use forms very securely. FortyTwo has an excellent example of how to add a dash of security when you’re building your forms.

<% form_for :user, @user, :url => {:controller => "users", :action => "update_email", :id => @user.id} do |f| -%>
	

<%= f.text_field :email %>

<%= submit_tag "Change" %>

<% end %>

Then inside the controller we update the user’s mail:

def update_email
   #all access and db logic handled with before filters
   if @user.update_attributes(params[:user])
     flash[:notice] = "We did it"
   else
   	 flash[:alert] = "Nope. We didn't make it"
   end
end

“When you are doing bulk updates like User.new(params[:user]) or user.update_attributes(params[:user]) you open the door to anyone updating important attributes that you only have (or should) have access to. In the above example someone can append user[:purchased_credits] = 1000 and make himself a gift.

Always secure your model’s important attributes from bulk updates using attr_accessible or @attr_protected* in the model declaration. And write tests about it. Always!”


Photo by 96dpi

9. Use to_param for SEO-Friendly Slugs

If you’re going to make your application public, why not make it as accessible as possible to search engines? Not only does this help the end user by eliminating variable gobbledy-gook in the URLs, but it also helps search engines figure out exactly what the page is going to be about.

You can achieve clean URL goodness with Rails with the slick to_param function.

	class Article < ActiveRecord::Base

	  def to_param
	    id.to_s+'-'+title.downcase.gsub(' ', '-')
	  end

	end

This automatically takes your title and makes a "slug" for it in the model of your application. Simple and easy.


Photo by tanakawho

10. Populate a Database with Test Data

After you're done writing your application, you're going to want to test it to make sure there isn't an abundance of bugs and other problems with what you've done. A good way to achieve this is to create a database and plunk a bunch of test data into it, so you can play with a demo site.

The excellent Railscasts site has a strong example of how to pull this off on an episode of their screencast. You can download the full source code along with the screencast and helper documentation. An excellent resource for any Rails developer, novice or pro.


Photo by 96dpi
  • Subscribe to the NETTUTS RSS Feed for more daily web development tutorials and articles.

Glen Stansberry is a web developer and blogger who's struggled more times than he'd wish to admit with CSS. You can read more tips on web development at his blog Web Jackalope.

Liked this post? Vote for it on Digg below. Thanks!


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://webpick.insicdesigns.com insicdesigns

    This is very useful. thanks

  • http://laminbarrow.com Lamin Barrow

    These are awesome techniques indeed.. Thanks

  • http://www.freshclickmedia.com Shane

    Nice to see more Ruby on here. To a C#/PHP programmer, the language may look a little ‘different’, but it’s got a certain elegance to it.

    Thanks.

  • http://james.padolsey.com James

    I’m definitely a Ruby noob, but I would just like to reiterate #7.

    As outlined in Yahoo’s “Best Practices for Speeding Up Your Web Site” it’s always best to place JavaScript at the bottom of your documents (just before </body>) – This means the JS will have access to all the DOM elements; you won’t need to use a DOM-ready function or window.onload!! … The only reason you should ever use the window.onload event is if you need to have access to properties of the window object, or if you need access to image dimensions within your document.

    Nice list Glen! :)

  • http://www.motionstandingstill.com Nahum Wild

    I initially did “5. Cache Unchanging Data at Application Startup” for my first signifigant app, but it slows down the app’s startup too much once it’s been under development for a while with this practice being followed. Just cache as you go, and use memcached.

    The less downtime the better.

  • http://smartic.us bryanl

    You mention moving javascript to bottom in the same post your mention RJS. :)

  • http://www.sazbean.com Aaron Worsham

    I’m a big fan of your third suggestion, grouping SQL statements into a transaction. One of the hidden talents of the Rails framework (IMO) is ETL applications because of the solid validations for models prior to db write. Grouping the writes into a transaction is a great way to commit those writes after validation with one statement to the DB.

  • http://mdeering.com mdeering

    #11 Railscasts, Railscasts, and more Railscasts. An episode was mentioned in #10 but everyone of the 100+ short FREE episodes has value.

  • http://webpick.insicdesigns.com insic

    Learning Ruby is really fun. thanks for this helpful tutorial.

  • http://www.ben-griffiths.com Ben Griffiths

    Loving Ruby so far, thanks for the tips :)

  • http://URL(Optional) sutch

    The snazzy images in this article alone make me want to build a Ruby on Rails application!

  • http://URL(Optional) Miles Johnson

    Including javascript at the bottom of any site never worked for me. Half of my content always needed the javascript at the top to work properly, I dont see how shaving off 0.5 seconds matters.

  • http://URL(Optional) Mark Wilden

    I think annotations like TODO: should be like any other comments. They should be used as little as possible. Basically, they’re an excuse for checking in code that isn’t done. Don’t do that. If you absolutely have to, file a ticket, which can be assigned business value and a developer. But don’t do that.

  • http://URL(Optional) charles

    I wonder what was cooler, the pics along the post or the post itself.
    Thanks for both…

  • http://URL(Optional) C.Korgan

    Ruby on rails is kinda slow in comparison to php. I mean … its good for small applications but it really sucks at medium or big applications. I don’t get what’s the big fuss about.

  • http://james.padolsey.com James

    @Miles, Shaving off 0.5 seconds is very important… Not everyone has broadband and a highly capable browser/computer. What method do you use to initiate your JavaScript? – I guarantee it’s slower (much slower if you use window.onload) than putting it at the bottom of the document!

    As long as you’re using modern techniques and abiding by coding standards, there is absolutely no reason why your JavaScript works in the HEAD but no at the bottom!

  • http://www.haykranen.nl/en/ Hay

    I love the fact that you put in these beautiful photographs with every tip, even though they don’t really relate or add anything useful to the article :)

  • http://paperplanes.de Mathias

    Putting TODOs, FIXMEs and the like in your code is the worst you can do to it. Noone will read them, noone will fix them. They’ll just keep piling up. Instead of writing the TODOs and FIXMEs, do it and fix it. Broken windows should be fixed ASAP.

    In place of the first point on the list I’d put “Utilize Rails’ Built-in Testing Framework”. Testing has never been easier than with Rails, and it’s the single most important tool to ensure that you can do those fixes without worrying about breaking something.

  • http://URL(Optional) jonny_noog

    Some good tips.

    However, when I first came to Rails, I was really interested in the whole RJS, write Ruby to produce JS stuff. But I soon realised that using RJS in its current form means littering your (X)HTML with inline JS. And it’s not very “progressive enhancement” friendly.

    For my current project I have chosen to try out Dan Webb’s Low Pro:
    http://www.danwebb.net/2006/9/3/low-pro-unobtrusive-scripting-for-prototype

    But one could just as easily go with jQuery et al. My point being that I love Rails but I think just about anything is a step up from the current implementation of RJS.

  • http://peepcode.com Geoffrey Grosenbach

    Re #9 to_param: Even better, use a plugin like Rick Olson’s permalink_fu to store the permalink upon record creation instead of calculating it each time. This also makes it possible to take the numeric ID out of the URL, too.

    http://github.com/technoweenie/permalink_fu/tree/master

  • http://URL(Optional) lowell

    non-ruby devs aren’t going to be familiar with the poster above me (g. grosenbach).. he develops a series of screencasts aimed at the beginning and intermediate rails developers.. not free, but you won’t hear any complaints on the interwebs, either.. check them out at peepcode.com

  • http://jamesbrooks.net James Brooks

    I’d modify your to_param method, as it won’t handle slashes and various other characters correctly. A good example can be located here:

    http://jamesbrooks.net/2008/09/01/slug-generation-in-rails

    Another alternative is to check out the slugifier being integrated into Rails, which is based off of this:

    http://github.com/henrik/slugalizer

  • http://techentreprise.com heri

    2. relic is too expensive for beginers. i’d recommend five runs tune up

    8. use attr_accessible (white list) instead of the attr_protected, it’s much more secure

    otherwise good article

  • Pingback: [root@EGA]# » Blog Archive » links - 20081028

  • Pingback: 10 Awesome Ruby on Rails Techniques to Get You Started | 极客社区-新闻博客

  • http://paperplanes.de Mathias

    heri: New Relic has changed their pricing model. The basic model is now free, and though TuneUp is cool too, New Relic’s RPM has a slight edge when it comes to monitoring. I for one can highly recommend it.

  • http://www.petercooper.co.uk/ Peter Cooper

    Why are there random giant photos in between each item?

  • http://garry.posterous.com Garry Tan (cofounder, posterous.com)

    I would also recommend query_reviewer: http://code.google.com/p/query-reviewer/

    Absolutely amazing for DB optimization. You need this to get a good idea of where all that DB query time is going.

  • http://www.webbogrfico.com WEBBOgrafico

    very useful tutorial, very beatiful photos

  • Pingback: mskari.org » Daily Summary 2008-10-29

  • Pingback: Полезные RoR советы | Gera-IT Blog

  • http://www.inovare.net Felipe Giotto

    Great techniques!

    It takes some time to become a good Rails developer! Scaffold it’s not enough! :D

  • Pingback: Speedlinking da Semana [26 Out a 1 Nov] - 2.0 WEBMANIA - Portugal, a Web 2.0, o Mundo e a Internet

  • http://goztansiyon.blogspot.com göz tansiyonu

    thanks for the article (:

  • Pingback: Top 50 Ruby on Rails Tutorials - Social Shopping, Design & Technology – StoreCrowd

  • http://creditright.blogspot.com right choice credit union

    thanks for the tutorials