Sep 3, 2008 3
Beware of Using named_scope for Associations
The named_scope feature in the Rails framework has been kicking about for a while now. Named_scope is a way to of narrowing down your more common find routines in your ActiveRecord models. Here’s a quick example:
In a task model we have the following:
named_scope :short, :conditions => ["duration < ?", 2]
end
This will allow us to query for all tasks that have a duration of less than 2.
Also we can setup a named scope that uses a parameter that we pass to it.
belongs_to :project
named_scope :short, lambda { |hours|
{ :conditions => ["duration < ?", hours] }
}
end
This will allow us to find tasks that have a duration less than the number of hours we pass to the named_scope.
Now while this is all great, I thought about changing some of my associations to use the named scope instead.
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :project
named_scope :for_project, lambda { |project_id|
{ :conditions => ["project_id = ?", project_id] }
}
end
We can now iterate through a collection of tasks associated with a project.
# do something here
end
Now while it did give me a chance to use named_scope within my project, something about the code just didn’t sit right. It’s hard to determine at first glance what we’re doing in the above code snippet, as the more conventional method is to find the project, and then access the list of tasks for that project. After adding a couple of more it seemed that the code didn’t read write in my eyes. A better way of find tasks for a project is to use the more conventional way in Rails. We can do this like so:
@project.tasks.each do |task|
# do something here
end
The features in the Rails framework are there to be used, but be careful your not using a feature in your project just for the sake of using it. There are plenty of ways of doing things in Rails, and usually that best way is the more conventional way of doing it rather than exploiting a featureof Rails just becuase you can.
My thanks to Max and Mike over at the RailsForum for their feedback.
Recent Comments