Advanced ActiveRecord Question

Hi Sunny,

Here's what I want to do:

1. I want to be able to store multiple fields into a single field. I'd
like to do it by adding a method call something like this during

class User < ActiveRecord::Base
  encoded_field :encoded_stuff {
    age => "23",
    hair_color => "black",
    eye_color => "brown"

Things like this are done in Rails all the time. The prime example is
storing passwords in a database. Typically a User model would have a
method called password= (a setter method) to set the password.

However, in the database itself, there is typically no password field.
There would be a salt and an MD5 hash of the password. The password=
method would update the salt and MD5 hash fields in the database. They
would be reference via self.salt and self.hash (or whatever the fields
are called in the database)

The model methods can, but do not necessarily, have to match exactly
what's in the database. The model is an abstraction on top of the
database model.

Let's suppose the encoded_field in the physical db is called
"encoded_data". There will be a method in the User model called

However, in the User model itself, you can also created methods called,
for instance:

age and age= (getter and setter that access the self.encoded_data method
to do its magic). Ditto for the hair_color / hair_color= and
eye_color / eye_color= methods.

You can then just add or remove methods from the model as needed.

As you get more comfortable with the dynamic nature of ruby, you'll find
that you'll be able to (possibly) create these getter and setter methods
on the fly as well (possibly based on another table in the
database ... :slight_smile: But, that's for another day.

The new edition of Agile has a good explanation of this with
password-based example.