Posts from has_many :through...

A simple alternative to namespaced models

A project I'm working on now is up to 57 model classes and is still growing. That's a lot of classes - welcome to domain modeling. In my opinion, the number of classes is a fair tradeoff that keeps each class simple enough to understand. In some ways it moves complexity out of the model class internals into the inheritance hierarchy, which is an important part of object-oriented design. I've worked on projects with many more model classes than that too. (Financial applications seem to require a lot of classes to model the complicated workflow and permission systems.)

The place where it starts to get hard to manage is when I look at the file system and see so many files in one directory. My brain usually starts to overload when I see more than a dozen or so classes in a directory. My first inclination is to throw some related class files into a subdirectory. The problem is that the standard way to do that in Rails is to put those models classes in a namespace (module). Rails used to have big problems with namespaced models, mainly with the dependency auto-loading code that finds class files based on the model class name. Most of those problems have been fixed, but there are still some usability issues with namespaced models.

Tags: activerecord, fixtures, rails

Symbols are not pretty strings

Symbols are one of the basic features of Ruby that give it that certain charm we all love. They aren't unique to Ruby (look at Smalltalk or Lisp), but they are a fundamental piece of the language. I'm not going to review what symbols are in this article since there are plenty of other explanations a short google away. However, I do want to say a few words about what I consider a common misuse of symbols.

The way I see it, symbols are great for naming things in your code, but bad for using as domain data. Over the last year or so I've seen a growing number of cases where symbols are used as an alternate syntax for plain old strings. I guess some people like to see :thing instead of "thing" in their code. Well, I don't like it. Sure you get to save a character, but at what cost? Won't somebody think of the children?

Tags: ruby, symbols

GitHubba-hubba

If you hadn't heard, GitHub had their public launch today. Congratulations to Chris, Tom and PJ on such an awesome product. I'm sure there's a bright future there.

I keep getting surprised by how different using GitHub is for me. Last week someone I never met or had even heard of found my migration_condordance repo and submitted a fixes for two bugs. It wasn't quite as big a thrill as my first kiss, but I sure got more of a rush from that than from seeing Beowulf in 3-D IMAX. On the other hand, when I saw someone else stopped watching my repo I was actually a bit sad. Yes, this is geek social networking with both value and impact.

You've probably heard that the Ruby on Rails is moving the official repo to GitHub. It's not active as of this writing, but give it a few hours. It's now active at http://github.com/rails/rails. I'm looking forward to seeing what this does to the contribution process. I expect there could be a rich ecosystem of forks of Rails where you can see a bunch of variations integrated into a consistent whole. A lot of folks keep what is effectively a fork of Rails, but it's often in the form of a collection of monkey patches. Using git means that those patches can be managed more effectively, and even made available to the public in a form that can be easily consumed. Then it becomes much easier to evaluate whether a change has enough support to justify including it in Rails core - just see how many people are actually using the change, instead of merely of the opinion that it might be useful. I don't know how to track how many people are using a repo that way, but I'm sure someone will think of something - maybe just a count of how many clones were made or tarballs were downloaded.

At any rate, today feels like some kind of milestone. Or perhaps a furlongstone.

Tags: github, sightings

simple pages

Simple things should be simple, complex things should be possible. — Alan Kay

Here's a tiny little tip for handling those boiler-plate pages that aren't part of your app's functionality but you usually need anyway. It's good for setting up about, contact, copyright, etc. You can always throw those pages into /public as static html files, but if you want them to get styled with layouts, they need to be rendered as actions. This is a way to do that simply. It's not rocket science, but I haven't done a noob post in ages and I'm getting over a cold and I haven't posted in too long so gimme a break.

Say you want to have a simple landing page and a few typical boiler-plate pages. Let's start with the routes.

In config/routes.rb

map.root :controller => 'home'
map.home ':page', :controller => 'home', :action => 'show', :page => /about|contact/

In app/controllers/home_controller.rb

def index
  # render the landing page
end

def show
  render :action => params[:page]
end

Throw your about.html or about.html.erb and other pages into app/views/home and you're good to go. If you've set up page caching, this won't even slow your app down.

The :page => /.../ bit in the route constrains it to match only those specific urls. If you want, you can change that to a constant, like HomeController::PAGES, so it's easier to manage.

If you want to link to those pages, you can use the route helper methods, home_path and home_url

link_to 'About', home_path('about')

You could always unroll the routes and have a separate route for each page, but I find this way a bit drier. But if you'd rather have a specific named route helper for each page, that's an okay way to go. Either way, you get to use layouts in your pages, and have a nice simple way to get them rendered.

Tags: rails

Migration Concordance

If you are a solo developer, Rails' migrations are the neatest thing since sliced bread. If you work on a team, you know that often it can be a real pain dealing with migrations. Someone on your team checks in a new migration and you don't notice it when you svn up or git pull, and suddenly all your tests are breaking. Or even worse, someone modifies an old migration and you need to reset and migrate up from zero (we're talking development here, not production). I'm not a fan of automatically running migrations (I'll leave the reasons for you to guess), but I do like to be informed of when I'm about to run headfirst into a wall. Saves so much wear and tear on my noggin.

And so I give you the migration_concordance plugin. It's pretty darn simple. From the README:

This plugin extends Rails migrations to provide notification when you need to run migrations. It will detect both new migrations and modifications to previously run migrations. It is primarily of use for team development, but is also useful when deploying a release to a new environment to determine when migrations need to be run. This plugin does not run migrations automatically, but will notify you whenever you need to run them.

Tags: migrations, rails

count vs length vs size

In Ruby, #length and #size are synonyms and both do the same thing: they tell you how many elements are in an array or hash. Technically #length is the method and #size is an alias to it.

In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.

That's I always have to look up these differences, so now I have them in one place so I don't have to think about it anymore.

By the way, today is my blog's second birthday. I just couldn't let that go by without a post!

Tags: associations, rails

Segregated page cache storage

Page-caching is one of the highest leverage features in Rails. It doesn't take much to set up, and the payoff is huge. When building Teldra I knew from the start that page caching would be part of my production deployment, as it should be for any site with pages where content changes infrequently relative to number of views.

The only thing I find annoying about using the page caching feature is how the cached pages are stored in the RAILS_ROOT/public directory, right alongside all the app's other static pages. I greatly prefer having the cached pages stored in a separate directory. This makes it a lot easier to distinguish between static pages and cached dynamic pages, and if something goes wonky with your cache you can blow it away easily with a single command.

Tags: caching, deployment, rails

UPDATE FEED URL FOR has_many :through

The has_many :through feed has moved. Please update your feed reader to use the feed URL http://feeds.feedburner.com/hasmanythrough

Feed readers are lame and URLs are forever

When I changed my blog software from Typo to Mephisto, my article and feed URLs all changed. I didn't want to break all those old URLs, so I put a lot of effort into writing a ton of Apache mod_rewrite rules to redirect the old URLs to the new ones. I set them up as 301 permanent redirects to indicate that the old URL was defunct and to use the new one from then on. That means that the feed reader is supposed to change the URL for the feed permanently. But feed readers are lame and many treat the redirect as a temporary change, so I'm still getting requests for feed URLs that haven't existed in over a year.

If you're reading this article in your browser because your feed broke and you came here to see what happened, that means it's time to update the URL for your feeds. I'm sorry, but your feed reader has been told every hour for the last year that the URL has moved to a new location forever, but it chose to ignore that fact, and I'm not going to keep supporting those old URLs anymore. Here's the new URLs so you can manually update your feeds:

The main feed is hosted on FeedBurner: http://feeds.feedburner.com/hasmanythrough (and has been for the last year).

Categories have disappeared and articles are now organized only by tags. Old categories are now just tags. Tag feed URLs look like: http://blog.hasmanythrough.com/tag/rails.atom

I haven't set up comment feeds yet, but they should be along in a week or two at most.

Tags: rails, routes, teldra

Speaking at RailsConf 2008

I received word this week that my talk proposal for RailsConf 2008 has been accepted. I'll be giving a talk called The Great Test Framework Dance-off. Doesn't that sound like fun?

Tags: conference, railsconf

One Hundred, Two Hosts, Three Engines

I started this blog nearly two years ago. In its first incarnation, it was running on the venerable Typo engine, hosted on DreamHost. About a year ago I switched over from Typo to Mephisto, still on DreamHost. Typo was a great start for me, and Mephisto was a good change when Typo was having some issues with the project. (Typo seems to be back on track these days, and has been for a while.) DreamHost was really cheap to get started on with hosting a Rails app, but I outgrew it in a couple months and have just been living in pain and denial ever since.

Now it's nearly two years later, and this is my 100th post on this blog. Coincidentally, it's another big transition for me. As of now this blog is hosted by the awesome force of nature that is EngineYard, and it's running on blog software of my own creation.

Tags: hosting, meta, teldra

Book Review: The Rails Way

Here's another entry in my ongoing Rails book review series.

Title: The Rails Way
Author: Obie Fernandez
Publisher: Addison-Wesley

The latest entry in Addison-Wesley's Professional Ruby Series is The Rails Way, by Obie Fernandez. The name is a nod to Hal Fulton's noble classic The Ruby Way, and it's clear this book aims to be as significant a feature in the Rails publishing landscape. The good news is that the book delivers, and then some. The Rails Way appears destined to become the new bible of Rails development.

Before I dive into the full review, a disclaimer. Obie is a friend and fellow cabooser, and someone I have a lot of respect for. I just want to get that out of the way so that no one can say I'm shilling for his book on the sly. But I'm glad I can give him a good review with a clear conscience. Anyway, back to the review.

Tags: rails, book, review

step, step, pivot, step

Wow, RubyConf was awesome. I'm sure by now you've read all the various blog reports on the sessions and the werewolf attacks. Aside from some stupid, amazingly loud all-night construction across the street from my hotel room, the conference was great and I had a superb time. It was very cool to see how far alternate Ruby VMs have come, and I expect the next year to be very interesting in that area. By the way, RejectConf has become too mainstream. What's up with doing it in a real conference room with A/V support and everything? And what about the beer?

Thanks to everyone who introduced yourself to me as a reader. (Though in the future you might want to wait until I've washed my hands and left the bathroom.)

The QCon panel last week was fun too. The topic was When is Rails an Appropriate Choice? James Cox did a nice job of running things, and I got to spend an hour talking with Obie Fernandez, Charlie Nutter and Ola Bini. (There were some last-minute changes in the lineup.) The panel was recorded on video, so I'm guessing InfoQ will make that available at some point.

Oh yeah, some news. Last week I started work at Pivotal Labs here in SF. Pivotal is a real powerhouse consulting firm specializing in web app development and does work in both Java and Ruby on Rails. The Rails developers there are top-notch and I'm really happy to be part of such a talented team. If you haven't been reading the company's coding blog Pivotal Blabs, you've been missing out. While I was having fun consulting and getting to work on lots of different things, I was missing having a regular schedule and co-workers who lasted more than a short time. This way I get the best of both worlds. I also get to work in an environment with a solid commitment to good development practices. My new job title is "Senior Agile Engineer", which should tell you something even if it mystifies the bank next time I apply for a loan.

Tags: events, pivotal, qcon, rubyconf

Self-referential has_many :through associations

This article updates a previous version for the Rails 2.0 way of things. Since there's not much difference, I decided to fix up the example code to be more understandable. After all, not everyone is a discrete math geek.

This example updates the one from the previous article. The only significant difference is that you don't need to specify the :foreign_key when using the :class_name option in a belongs_to association. In Rails 2.0, the key is inferred from the association name instead of the class name. I also included the :dependent option because I feel it's too often overlooked.

These classes could be used to model a food chain. Spider eats fly, bird eats spider, cat leaves bird on pillow as gift...

create_table :animals do |t|
  t.string :species
end
create_table :hunts do |t|
  t.integer :predator_id
  t.integer :prey_id
  t.integer :capture_percent
end

class Animal < ActiveRecord::Base
  has_many :pursuits,  :foreign_key => 'predator_id',
                       :class_name => 'Hunt',
                       :dependent => :destroy
  has_many :preys,     :through => :pursuits
  has_many :escapes,   :foreign_key => 'prey_id',
                       :class_name => 'Hunt',
                       :dependent => :destroy
  has_many :predators, :through => :escapes
end
class Hunt < ActiveRecord::Base
  belongs_to :predator, :class_name => "Animal"
  belongs_to :prey,     :class_name => "Animal"
end

The Hunt model describes how likely a species of predator is to catch a species of prey. From the predator's perspective the hunt is a pursuit, but the ever-hopeful prey sees it as an escape. Note that you can model both kinds of hunts between the same pairings of animals: Some days you get the bear, some days the bear gets you.

Tags: associations, rails, update

RubyConf and QCon

RubyConf 2007 is just a few days away. I'll be there in Charlotte, basking in the Ruby love. If you're there, do say hi. I always like meeting my readers.

Also, I'll be at QCon in San Francisco next week. On Friday afternoon I'll be speaking on James Cox's panel: When is Rails an Appropriate Choice?

Tags: conference, events

Book Review: Pro Active Record

I've been wanting to start doing some book reviews for a while, so here goes. The folks at Apress have been kind enough to send me review copies of a couple books, so I'm going to start with one of them. First up, Pro Active Record.

Title: Pro Active Record: Databases with Ruby and Rails
Authors: Kevin Marshall, Chad Pytel, Jon Yurek
Publisher: Apress

My first thought at seeing this book was, "Hey, a book all about ActiveRecord! Cool!" It's nice to finally see a volume dedicated to ActiveRecord, since it's my favorite part of Rails. However, this book ends up being something of a mixed bag. There's a lot of good information in it, and it does a decent job of covering all the basics. There are even some excellent parts here and there. But the book also has some problems, so it's hard for me to give it an unequivocal recommendation. Nevertheless, it does have value and fills a needed spot, so it may be what you're looking for.

Tags: rails, activerecord, book, review

MicroPlace: invest wisely, end poverty

And now for something completely different... I'm talking about the launch today of MicroPlace, a new website which was written in Rails. I don't usually call out such sites, but this time is different for a few reasons. Firstly, I helped build the site, so I have a personal involvement in it. Secondly, it's a good cause that's worth talking about. And lastly, the circumstances of its creation should be of interest to the Rails community.

Tags: rails, sightings, microplace

Simpler than dirt: RESTful Dynamic CSS

Way back when, I wrote about how to do Dirt Simple RCSS in Rails. Now that Rails 2.0 is upon us, it's time to get even simpler. With all the restful magic in Rails 2.0, you can get even simpler than dirt.

Let's assume you have a restful User resource. You've got your "map.resources" in routes.rb, a typical User model, and a Users controller with standard views like index and show. Now you want to generate user-specific css based on state in the user model.

1) Create a view template called "show.css.erb". For example:

p {
  color: <%= @user.color %>;
}

2) Add a css format option to the respond_to block in the show action of the UsersController. You only need the default behavior for the css format, since all you need to do is render the view.

def show
  @user = User.find(params[:id])
  respond_to do |format|
    format.html
    format.css
  end
end

You can see the dynamically generated css at a url like /users/1.css in your browser.

Here's how to use the stylesheet in a view, assuming you've set up a @user object:

<%= stylesheet_link_tag formatted_user_path(@user, "css") %>

Told you it was simple.

Note: Geoffrey "topfunky" Grosenbach also has a good article on dynamic CSS, which includes a nice screencast as well.

Tags: css, rails, update

Everything old is new again

As you've likely seen in your feed reader about 50 times already, Rails is turning 2.0. The Preview Release has just been announced, which means that 2.0 final is just a few release candidates away. So much has changed over the last year or so that a lot of the older material on this blog is out of date and needs updating for the reality of 2.0. Seems like now is a good time to get going on the rewriting. I'll be digging in and bringing stuff up to date over the next few weeks (months? there are quite a few articles after all).

Here's the list of articles I'm going to be taking a look at. I'm not certain that all need updates, but I think most of them do. If you have a request for something in particular for me to work on sooner, just leave a comment and I'll take that into account. Of course, I'll be updating the Many-to-many Dance-off first!

Tags: meta, rails

it's easy being redgreen

I can't get by without redgreen to colorize my test output. You can get it to work with all your Rails test tasks by requiring the redgreen gem in test_helper.rb. The problem is, it messes up your test output formatting when you run tests in TextMate using Command-R. The solution is trivial - check to see if any of the TextMate execution environment variables are present:

In test_helper.rb:

require 'redgreen' unless ENV['TM_MODE']

Now back to your regularly scheduled internets...

Tags: tools, textmate
next page »