Rails Notes

I got interested in Rails a year or so ago when I first started hearing the hype, and I dug into it a little bit.  At the time, I came to the conclusion that while the Ruby language was pretty slick, Rails itself was basically a code generation engine that would become more hindrance than help on a real project.

Recently I started in on a new little side project and decided to give Rails another chance.  This time around, I followed along with a book, Ruby on Rails: Up and Running, which isn't a great book, but for someone who is already marginally familiar with Rails, it serves pretty well.

Up and Running made a couple of things clear to me.  One is that the power of Ruby is in it's O-R mapping, Rake migration, and ActiveRecord.  I also discovered script/console.

The script/console script gives you an interactive command-line inside your application. You can create model objects, execute methods on them, and see the results interactively.  For example, in my model I have a User, a Log, and a LogLine.  I can explore these objects and their relationships in the console:

[butler]$ script/console
Loading development environment.
>> u = User.find_by_login('stevex')
=> #<User:0x4119dbec @attributes={"login"=>"stevex", }>
>> u.logs.size
=> 1
>> u.logs[0].log_lines.size
=> 6

(The >> lines are ones I typed).  That last line is doing a fair bit of SQL for me, but it's all hiding behind the ActiveRecord relationships.  Some people think that's a bad thing, but if this ends up being too slow I know how to make it faster, and for now, RAD is more important than performance.

Considering Rails' poplularity, it's surprisingly hard to find good information online.  The best source for solutions to real problems is looking at other people's code, so this Ruby source browser is a pretty good resource.

And here's a little tip for something that I spent a stupid amount of time trying to figure out considering how simple it was.  Routing in Rails lets you redirect requests based on URL content.  You can basically parse parameters out of the URL and then select which controller and what action on that controller based on that information.  For example, here's a line from my config/routes.rb:

map.connect 'log/:login', :controller => 'log', :action => 'logview'

This line says that for a URL that looks like "log/stevex", to use the "log" controller, the "logview" action, and pass the text after "log/" as a parameter named :login.

But where do you find that parameter?  It's not passed as a paramter to the logview function.

It's accessible via the params array.  For example:

def logview
  @login = params[:login]

Simple enough once you figure it out..