Three ActiveRecord Model Utility Methods

Lately I’ve found myself implementing at least two out of three of these utility methods on most of my ActiveRecord models on my Rails apps. These methods leverage functionality of either Ruby by itself or Rails that will become helpful in other parts of your application.

The labeler: #to_s

Defining a to_s method enables a very clean way to display a label that represents your model instance. Suppose you have a Post model. You could define a #to_s method similar to the following:

1
2
3
def to_s
title
end

Now your views can simply do something like the following HAML:

1
2
.post
.h2= @post

The quantifier: #<=>

This method is useful when you consistently need to be able to respond to the question “Which of these is bigger/better/taller/fatter/purtier?”. Which metric defines the quantity is completely up to you, but what’s important is that defining this method will allow you to call the Enumerable goodies #min, #max, and #sort. For example, and following the Post model example above, you could imagine the following method definition.

1
2
3
def <=>(other)
rating <=> other.rating
end

Assuming you have a recent named_scope that returns the latest n posts, you could do things like Post.recent.max or Post.recent.sort.

The SEOer: #to_param

Finally, this method is leveraged by Rails itself. You can take advantage of the fact that the :id parameter on Rails URLs can be any sequence of integers followed by any non-whitespace characters. Rails will ignore any character after the integers, and use that as the :id parameter. It is customary to use the post’s title as part of the URL. An easy way to achieve this in Rails is to define the following method on your model:

1
2
3
def to_param
"#{id}-#{title.parameterize}"
end

Rails will call to to_param method when using post_url(@post), and your URLs shal become slugs, in SEO terms.