Touch me: cleaning up Rails association code

Yeah, this is one of those posts where I stop wittering on about what I’ve seen at the theatre or in the cinema, and talk about computer code I’ve been writing. Odd mix for a blog, I know: welcome to my world…

In a Rails project I’m currently working on, I have a parent object that has a :has_many collection of children. In this case, they’re all time based, so let’s call the parent class Calendar and the child association Event:

Class Calendar < ActiveRecord::Base
  has_many :events
end

Class Event < ActiveRecord::Base
  belongs_to :calendar
end

(As you may have guessed, these aren’t the real class names. Confidentiality, and all that.)

Many operations on our Calendar object rely on the overall date range between the first and last dates in the list of events. Now we can, if we want to, calculate those on the fly using associations:

Class Calendar < ActiveRecord::Base
  has_many :events

  def first_date
    events.order('starts_on ASC').first.starts_on
  end
end

…and so on. Again, we have quite a few of these methods, and they’re actually a bit more complicated than this.

Continue reading Touch me: cleaning up Rails association code

Expirations

So I’ve been thinking lately that I should scrap this blog. I so rarely use it any more – instead using my [work blog](http://blogs.thestage.co.uk/tvtoday/), [Twitter](http://twitter.com/scottm), Facebook, Flickr and UncleTomCobleyAndAll.com. Most of the traffic is to a few old posts, whether it’s to [the `simply_helpful` plugin](http://matthewman.net/2006/09/04/new-rails-feature-simply_helpful/) whose functions are now built-in to Rails 2.x, or [long-forgotten memes](http://matthewman.net/2005/05/03/bad-wolf-hunting/).

Maybe I’ll do something new with this place. In time.

For now, on the subject of expiration, I’m linking to [this comment](http://railspikes.com/2008/9/29/an-experiment-with-page-caching#comment-1738) at the base of a post about Rails’ different caching methods, and their expiration techniques.

> One very useful way to avoid the dog pile is to expire behind. Similar to a write behind cache, on checking a ttl and finding the content expired, still serve up the stale content for that request, but also asynchronously start rebuilding the content via a queue/background worker. If you randomize your ttl’s a bit this results in very even system load.

To me, this makes great sense, especially in the context of an application I’m working on at the moment. So I’m linking it here not so much so I can find it again, but in the hope that the concept’ll permeate into my subconscious as I’m coding.