Scopes (Not the Monkey Trial) in Rails 3

Post by: on February 19, 2011 | 0 Comment

OK, bad pun. This is the life I lead.

Tonight was the first time I’ve gotten to use the Scopes feature in Rails. I’d heard about named_scopes a while back, but hadn’t gotten to a point where I needed one, so I didn’t really know how they worked, despite skimming a few articles on them.

I started with the Railscast on named_scope, which is a great intro, but I soon discovered that they’d changed the syntax in Rails 3. Fortunately I had enough of a grasp on it by then that I was able to change my code to the new style with the help of EdgeRails.info.

It was an easy change, and made my code much cleaner.

What I did was add a ‘today’ scope to the slot class, so that I can grab all slots for a given day like so:


scope :today, lambda {
dt = Date.today
where("slots.start_at >= ? AND slots.end_at
dt.beginning_of_day, dt.end_of_day)
}

I had to use a lambda in there so that the date code would evaluate when the scope was called, not when the class was first loaded. The syntactic sugar that Rails adds for date handling is wonderful, it makes the code quite a bit easier to read.

That’s it for tonight, I’ll hit the low hanging fruit on appointments in the morning.

Categories:Uncategorized