Friday, April 27, 2007

Association extensions tidy up your Rails models

Don't underestimate the power of association extensions when building your rails models. I totally glossed over them until recently.

Consider this class:

class Project < ActiveRecord::Base
has_many :stories do
def backlog
self.select { |s| s.iteration.nil? }
end
end
end


With this model you could say:
my_project.stories.backlog

As an alternative, you could put all the logic in the controller. This would, of course, violate Jamis Buck's 'Skinny Controller, Fat Model principle'.

Another alternative - use a more flat api style:

class Project < ActiveRecord::Base
has_many :stories
def backlog
self.stories.select { |s| s.iteration.nil? }
end
end

...and then you'd call it thusly:
my_project.backlog

The benefit of utilising association extensions is that methods will be grouped together more naturally, and tend to be shorter as a result of their context. The larger your model the more this will benefit you.

See more great examples of this in explainpmt - an open source web-based tool.

No comments: