2 things every ActiveRecord model needs to know

If you’re an ActiveRecord model, life’s pretty easy.

Find yourself here, save yourself there, validate yourself every now and then.

But there are two questions that every ActiveRecord model needs to know the answer to, otherwise they find that they’re just that bit awkward when dealing with the outside world.

The first is pretty easy … “who are you?”

In other words – how do you represent yourself as a string?

The way to do this is to override the to_s (to-string) method.

For most models, there should be some sort of natural representation … for example:

For some models, you may need to be a bit more creative; this Connector sits between an outlet and an inlet, so we can use those to describe it:

The other thing every ActiveRecord model should know is “how do you describe yourself to a computer?”

In other words, give me a unique representation of yourself that I can use as a reference to you…

This is particularly useful in Rails applications when you want to reference the model in a URL. But it can be used elsewhere – maybe you’re generating a report for a person, so you need to come up with a filename for that report.

Because of the first requirement, Rails offers an easy place to do this – override to_param – and because URLs and filenames also have some strict requirements on legal characters, it offers a method on String, parameterize that keeps things safe.

Lastly, we want these references to be as unique as possible – if you use it in a URL then you want to be able to find that model in the database. That’s why the default implementation of to_param just returns the database ID. An easy to use identifier, but not very readable for humans.

So what can we use that’s better?

How about…

… and …

We still use the database ID but we add some meaningful text to it (our previously defined to_s). So our URLs become something like http://example.com/people/123-gordon-gecko or http://example.com/connectors/789-this-to-that. And even better, as the representation starts with the numeric database ID, we can just pass it to the ActiveRecord find method in our controller, it will convert it to an integer and locate our record for us:

Two things every ActiveRecord model should know to make talking to the outside world just that little bit more pleasant.