Archives

ActiveRecord Association Extensions

Posted by on Thursday 25 Jan 2007 .

Permalink | rubyonrails | got something to say?

We were discussing how to improve the following code on the #ror_au channel today:

class Category < ActiveRecord::Base
def self.simple_options(id)
options = Option.find(
:all,
:conditions => ["category_id = ?",id],
:order => "sort")
return_options = []
for o in options
return_options << o if o.in_simple == 1
end
return return_options
end
end

First, simple_options is a class method, but is always called within the context of a single category. This is achieved in the code above by passing a category id to the class method, but in OO languages we typically achieve this through the use of an instance method:
class Category < ActiveRecord::Base
def simple_options
options = Option.find(
:all,
:conditions => ["category_id = ?",id],
:order => "sort")
return_options = []
for o in options
return_options << o if o.in_simple == 1
end
return return_options
end
end

Given that the condition on the find is scoping the options to a category, we can use an association to handle the scoping for us:
class Category < ActiveRecord::Base
has_many :simple_options, :class_name => "Option",
:order => :sort
end

Now we're missing the further scoping handled by the for loop that prunes the result set down to those records where in_simple == 1, so let's add a condition.
class Category < ActiveRecord::Base
has_many :simple_options, :class_name => "Option",
:order => :sort, :conditions => "in_simple = 1"
end

There, isn't that nicer. But the subject of this post is association *extensions* which I haven't touched on yet. Given that there's a second class method for Category, self.advanced_options, we can use association extensions to our advantage to scope simple_options, and advanced_options to a single association:
class Category < ActiveRecord::Base
has_many :options, :order => :sort do
def that_are_simple
find(:all, :conditions => "in_simple = 1")
end
def that_are_advanced
find(:all, :conditions => "in_advanced = 1")
end
end
end

So now for any instance of a Category we can refer to options.that_are_simple, and options.that_are_advanced. Doesn't that make you feel all warm and fuzzy inside.

Rails::Configuration Options

Posted by on Friday 12 Jan 2007 .

Permalink | rubyonrails | got something to say?

Nathan de Vries wrote a script today that lists all supported Rails::Configuration options that are available for customisation in your Rails::Initializer block. Very handy if you don't want to have to dig through the source to find what options are available.

Thanks Nathan!