A Note About Rails Versions 3

Jeffrey Hardy,
Dec 18, 2007

As some of you may be aware, Rails 2.0 was recently released. This is a huge milestone for the Rails project, but it introduces a few changes that are sure to trip up readers.

The book was written for Rails version 1.2.3

That’s right. When the book was written, Rails 2.0 was merely a glint in the core team’s eye.

Generally, a release that increments the major version number (as in Rails 1.x to 2.0) will include breaking changes, and Rails 2.0 is no exception. With this latest release, the core team has been really aggressive in terms of removing features. Some of the nice-to-have features like scaffolding and pagination that we wrote about in the book are no longer part of the core framework but are available as plugins instead.

Installing and using Rails 1.2.3

If you want your sailing to be smooth, I recommend installing and using Rails 1.2.3 as you go through the examples in the book. Here’s how you would go about installing version 1.2.3 via RubyGems and telling your application to use it:

  1. sudo gem install rails -v 1.2.3
  2. open config/environment.rb and make sure the RAILS_GEM_VERSION is set to 1.2.3:
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '1.2.3'

You’ll no longer need to worry about installing the scaffolding or pagination plugins because they’re both alive and well in Rails 1.2.3.

You can also elect to freeze a copy of Rails into your project’s vendor directory, which will take precedence over the Gem version you’ve specified. Rails makes this easy with a bundled Rake tasks:

$ rake -T | grep freeze
rake rails:freeze:edge  # Lock to latest Edge Rails or a specific revision with REVISION=X
rake rails:freeze:gems  # Lock this application to the current gems (by unpacking into vendor/rails)
rake rails:unfreeze     # Unlock this application from freeze of gems or edge and return to a fluid use of system gems

As you can see from the comments, you can freeze to either the edge version of Rails, or a specific revision from the repository. You can also freeze to whatever Gem version of Rails you have installed on your system.

This is often called the vendor everything approach.

What about the future?

Take heart. Most of the changes are minor enough that you won’t have any trouble transferring your knowledge to Rails 2.0. By the time you’ve finished the book, you’ll have a much better understanding of Rails, and to be sure, the fundamentals haven’t changed.

The new and refined features of Rails 2.0 have only made it better.

Problem: pagination

Jeffrey Hardy,
Dec 11, 2007

On page 172 of the book, we talk about Pagination. Pagination is a good thing. As a rule, don’t return more results from the database than you need to for a given purpose.

In the sample application, we use Rails’ built-in Paginator, but with the caveat that it might be slated for future removal from the framework. Alas, that day has come. In Rails 2.0, pagination is no more. Why? Well, as I mentioned in the book, a lot of folks feel that pagination is too domain-specific to be part of the framework.

You can install the classic_pagination plugin, which is the extracted code from Rails, rolled into a plugin. This is what we used in the book. Installation is the same as for any plugin:

./script/plugin install svn://errtheblog.com/svn/plugins/classic_pagination

That’ll get you up and running with the examples in the book. This has bitten at least one reader already. Read up on the thread on the book’s mailing list

Enter: will_paginate

Pagination was removed from Rails because it was deemed outside the scope of the framework. This is good. Removing a feature like this is usually a catalyst for the emergence of better alternatives. Out of the handful of pagination plugins currently circulating, my favorite is will_paginate:

http://errtheblog.com/post/4791 http://require.errtheblog.com/plugins/browser/will_paginate/README?format=txt

This is from will_paginate’s README:

# app/controllers/posts_controller.rb

@posts = Post.paginate :page => params[:page]

# app/views/posts/index.html.erb

<p>Handful of posts coming up</p>
<%= render :partial => 'post', :collection => @posts %>

<p>Now let's render us some pagination!</p>
<%= will_paginate @posts %>

Note that will_paginate’s interface is different than that of classic pagination, so it’s not a drop in replacement. Still, if you read the examples in the README, you should be able to figure it out in no time!

On sessions, cookies, and debugging in Rails

Jeffrey Hardy,
Nov 28, 2007

To borrow a move from Ruby Inside, here are a few Rails tidbits that don’t need separate posts, but that you’re likely to find quite useful when learning Rails.

Everything you need to know about sessions and cookies

This article is long. But it’s the best writeup on sessions and cookies as they pertain to the Rails framework I’ve yet read.

http://www.quarkruby.com/2007/10/21/sessions-and-cookies-in-ruby-on-rails

Debugging Rails applications with ruby-debug

The days of the breakpointer are long behind us. The new tool on the block is ruby-debug. Thankfully, Patrick Lenz has written the most complete guide to ruby-debug I’ve seen to date.

Debug your Rails app with ruby-debug

Ruby Naming Conventions

Jeffrey Hardy,
Oct 19, 2007

From the Softies on Rails comes a quick summary of idiomatic Ruby naming conventions. To a seasoned Rubyist, these are common knowledge, but I’ve seen many a beginner carrying their baggage from other languages over to Ruby.

Ruby 101: Naming Conventions

In the book, I wrote the following sidebar that covers the basics (from page 330):

Ruby Style

Style is important when programming. Ruby programmers tend to be picky about style, and generally adhere to a few specific guidelines:

  • Indentation size is two spaces
  • Spaces are preferred to tabs
  • Variables should be lowercase and underscored: some_variable, not someVariable or somevariable
  • Method definitions should include parentheses and no unnecessary spaces: MyClass.my_method(my_arg), not my_method( my_arg ) or my_method my_arg

Whatever your personal style, the most important thing is that you remain consistent. There’s nothing worse than looking at code that switches between tabs and spaces, or mixed and lowercase variable names.

Beginning Rails on Sale at Bookpool

Jeffrey Hardy,
Oct 4, 2007

Apress is having a huge sale at BookPool this month – pretty much all their titles are 50% off. This includes, of course, Beginning Rails, for the ultra-low price of $17.25. If you’re thinking about getting into Ruby on Rails and are looking for a great book to get you up and running, now is a great time to take the plunge.

Beginning Rails at Bookpool

Becoming an Expert in Rails is Hard

Jeffrey Hardy,
Sep 30, 2007

Jay Fields has an insightful article on the fact that, while it’s relatively easy to get started with Rails, experts aren’t born overnight.

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.

Reading Beginning Rails will not make you an expert. It will introduce to you the Rails philosophy, and take you through the basics, but in order to build a successful web application using Rails, you need to become proficient in a lot of technologies. Web applications have a lot of moving parts. In addition to learning Ruby, you’ll need to learn SQL, JavaScript, Ajax, HTML, and YAML, and a collection of others. You’ll also need to learn how to test, and how to debug. If your web application is to become popular, you’ll need to learn how to scale it in a production environment and how to optimize your database server.

There is no shortcut to success here. Mastering web development takes time and effort. Reading a book like Beginning Rails is really only the first of many investments in your knowledge portfolio, something that requires constant investment over time.

Read the full article at Jay’s blog here.

Raaum's Rails Reader

Jeffrey Hardy,
Sep 28, 2007

Raaum’s Rails Reader is a great resource for beginners and experienced Rails developers alike. It serves a both a manual for Rails and a field guide to help you navigate the wealth of other Rails documentation scattered throughout the web.

http://rails.raaum.org

Some choice cuts include:

Thanks Raaum!

Rails Console Secrets

Jeffrey Hardy,
Sep 19, 2007

This is an oldish link, but it’s a good one, especially for those folks who aren’t yet Rails console ninjas.

Secrets of the Rails Console Ninjas by Amy Hoy.

For the unenlightened, Ruby comes with a an interactive interpreter called irb (for Interactive Ruby). Rails harnesses the power of irb to give you an interactive console for your application (hereafter referred to as simply “the console”). The advantage of the console is that it enjoys the special privilege of being fully integrated with your project’s environment. This means it has access and knowledge of your models (and subsequently, your database). You can execute any arbitrary Ruby code inside the console and do anything you might otherwise do inside your Ruby programs: set variables, evaluate conditions, and inspect objects. The only essential difference between an interactive session and a regular old Ruby program is that console will echo the return value of everything it executes. This saves you from having to explicitly print the results of an evaluation. Just run the code, and you’ll see the results.

We use the console pretty heavily in the book, so for the most part, you learn by doing. But there are definitely some tricks here that we didn’t mention. So, if you’re wondering about things like:

  • Specifying console environment (./script/console production)
  • Getting out of a block of code (ctrl + c)
  • Accessing the last return value (_)
  • Reloading the console (reload!)

Then you should check out Amy’s article. There’s also a collection on Stupid console tricks!

For further reading, check out Chris Wanstrath’s classic article irb Mix Tape, which is full of other amazing goodies that will make your day.

Source code and errata updated

Jeffrey Hardy,
Sep 11, 2007

I’ve updated (and corrected) the source code for the book.

At the request of readers, I’ve now included the individual code listings for each chapter (previously, I’d included only the finished, sample application in its entirety). In addition to the app, the code archive now contains all the listings, (named for their listing numbers and filename), divided into directories by chapter. So, if you’re looking for Listing 3-5 from Chapter 3, you’ll find it in chapter03/3-5-event.rb. Observe:

j:~/book/source$ ls
README      chapter01   chapter03   chapter05   chapter07   chapter09   chapter11
application chapter02   chapter04   chapter06   chapter08   chapter10

j:~/book/source$ tree chapter03
chapter03
    |-- 3-1-database.yml
    |-- 3-2-001_create_events.rb
    |-- 3-3-001_create_events.rb
    |-- 3-4-events_controller.rb
    |-- 3-5-event.rb
    `-- 3-6-events_controller.rb

0 directories, 6 files

You get the idea.

This should make things a lot easier if you’re following along with the code in the book. Also note that I’ve been able to correct all the bugs/typos/errors in the code (which is much more forgiving than print). The errata list is nearly complete too, so if you’re reading the book you’ll want to check that out lest you get tripped up by something.

The source code and errata will always remain available at these locations:

The permanent links are over there in the sidebar.

Dynamic Scaffolding and Edge

Jeffrey Hardy,
Sep 5, 2007

We talk about dynamic scaffolding in Rails starting on page 54, Up and Running with Scaffolding, but we need to mention something: the dynamic scaffolding we’re using has been moved out of Rails core and into a plugin.

Now, don’t panic. This won’t affect you if you’re using the latest stable version of Rails (1.2.3 at the time of this writing), but if you’re using edge Rails, it will.

Fortunately, installing the scaffolding plugin couldn’t be any easier:

./script/plugin install scaffolding

The plugin script tries to look for plugins in certain locations, including the Rails svn URL (try ./script/plugin sources to see the complete list of sources). If for some reason it fails to find scaffolding by name, you can always use the full path:

http://svn.rubyonrails.org/rails/plugins/scaffolding

If you’re following along with the book using edge Rails, you’ll need to install this for the examples to work!

(I’m actually a fan of the dynamic scaffolding. I find it useful to be able to tweak my schema and model and play with it before generating boilerplate templates. Actually, I tend to use dynamic scaffolding more that the generated variety. Just my personal preference, though.)

Cheatsheets

Jeffrey Hardy,
Sep 5, 2007

I was going through some bookmarks today and I came across a few cheatsheets that I thought would be of interest to readers.

First, there’s Jens-Christian Fischer’s PDF cheatsheet for Rails. It doesn’t cover version 1.2, but most of the information is still relevant. When you need to look something up quickly, you can just search the PDF. Handy.

Another Rails cheatsheet I really like is from ilovejackdaniels.com. It’s a good quick reference that includes the default directory structure, predefined variables, reserved words, and more. Definitely one to check out.

If you’re looking for a Ruby-only cheatsheet, try RubyCheat on for size. And while technically not a cheatsheet, I also find ZenSpider’s Ruby QuickRef pretty useful when the PickAxe is not handy.

Choice Gem: cheat

Speaking of cheats, one of my favorite Ruby Gems as of late is Chris Wanstrath’s cheat.

As with all Ruby Gems, it’s easy to install:

$ sudo gem install cheat
Bulk updating Gem source index for: http://gems.rubyforge.org
Successfully installed cheat-1.2.1

Basic usage is straightforward: you run the cheat program and give it the name of the cheatsheet as an argument. So, if you forget all your MySql commands, you can just run cheat mysql.

Here’s another example, and one I use all the time—strftime (output truncated, of course):

$ cheat strftime
strftime:
    %a - The abbreviated weekday name (``Sun'')
    %A - The  full  weekday  name (``Sunday'')
    %b - The abbreviated month name (``Jan'')
    %B - The  full  month  name (``January'')
    ...

There are a bunch of Rails-related sheets which you can see by typing cheat rails. Here’s the full list:

  • radrails_rhtml
  • radrails_ruby
  • rails_console
  • rails_edge
  • rails_request_object
  • rails_reserved_words
  • rails_tasks
  • rails_to_s
  • rails_vim
  • test_spec_rails
  • textmate_rails

So, if you’re trying to check out a working copy of edge rails, but forget the path to the Rails subversion repository, you can quickly type cheat rails_edge to be reminded.

To see all available cheatsheets in a big long list, do this:

$ cheat sheets
All Cheat Sheets:
  arts
  as3_formulas
  ascii
  assertions
  assert_select
  association_methods
  awk
  balloon
  bash
  ...

Finally, to see more of what you can do with cheat, including examples and useful command line flags, use cheat’s own cheatsheet:

$ cheat cheat
cheat:
  Hey, welcome to cheat (http://cheat.errtheblog.com).
  Thanks for trying it out. 
  ...

Happy cheating!

Reviewed on Digital Web

Jeffrey Hardy,
Sep 4, 2007

Matthew Pennell has written a thorough review of Beginning Rails over at Digital Web Magazine.

For a Rails novice, what follows is a series of head-shaking, “That’s cool!” moments, as the book walks you through the basics of developing with Ruby on Rails; using the built-in web server, auto-generating files, finding your way around the interactive console, using the scaffolding feature (which allows you to create an entire database front-end with only one line of code), and creating and managing database migrations are all smoothly covered.

I’m a regular reader of Digital Web, so I was happy to see it reviewed there. But don’t take my word for it. Read the full review.

Mailing List

Jeffrey Hardy,
Aug 28, 2007

Attention Readers! I’ve set up a mailing list via Google Groups to serve as a support channel for the book:

http://groups.google.com/group/beginning-rails

If anyone has any questions or needs any help, subscribe to the list and post away!

Unknown database bug in Chapter 2 1

Jeffrey Hardy,
Aug 14, 2007

Or, Rails without a database.

I found the first bug in the installation instructions for Beginning Rails. If you’re having trouble running the inaugural application (aptly named hello), it’s probably because we forgot to mention that Rails expects a database.

Without the hello_development database, browsing to http://localhost:3000/salutation/hello will result in something like this:

Mysql::Error (#42000Unknown database 'hello_development'):
/usr/local/lib/ruby/gems/1.8/gems/activerecord/lib/active_record/vendor/mysql.rb:523:in `read'

In the interest of making apparent the irony, I draw your attention to the first paragraph of the chapter in question:

For various reasons, Rails has gained an undeserved reputation of being difficult to install. We want t dispel this myth.

Well, so much for dispelling the myth!

Remember how in the installation instructions we said that Rails was downright stubborn about working without a database? Well, we were right. Here Rails is obviously expecting a database called hello_development, but we didn’t create one!

There are two ways to fix this problem. You can either:

  1. make Rails happy by creating the required database, or
  2. edit Rails’ config file and tell it you’re not using a database for this application

Creating the database is perhaps the easiest way to go. You can flip ahead a few pages and read up on how it’s done, starting on page 47. But, if you’re impatient like I am, (and if you followed the installation instructions), you should be able to create the hello_development database thusly from the command line:

mysqladmin -uroot create hello_development

Stop the server using CTRL-C, and restart it using ruby script/server. Reload http://localhost:3000/salutation/hello and see if it works. If it does, great. Let’s just pretend this little mishap never happened. If it doesn’t, we’ll have to edit the config file.

Rails’ main config file is located in config/environment.rb. To configure Rails not to bother with a database, open it up in your text editor of choice and find the (commented out) line that reads:

# config.frameworks -= [ :active_resource, :action_mailer ]

Remove the comment and modify the line so that it excludes only ActiveRecord.

config.frameworks -= [ :active_record ]

Again, stop the server using CTRL-C, and restart it using ruby script/server. Reload http://localhost:3000/salutation/hello and all should be well.

Apologies for this ironically placed blunder!

Starting Rails: what Kalid Azad wishes he'd known 1

Jeffrey Hardy,
Aug 7, 2007

I just came across Starting Ruby on Rails: What I Wish I Knew in which Kalid Azid summarizes what to expect from Rails and its relatives, including Rake, IRB, and YAML. Also mentioned are various Ruby-isms and Rails-isms that often elude the novice developer.

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.

This is the exact question I asked myself while writing Beginning Rails: what do you wish you’d known when you first started out. So, if you’re reading the book and are wishing for a concise summary of some of the various gotchas, do yourself a favor and read Kalid’s article.