Re: Advanced ActiveRecord Question

Rick Tessner
Sun, 24 Dec 2006 01:24:44 -0000

Hi Sunny,

On Sun, 2006-24-12 at 00:54 +0100, Sunny Hirai wrote:

> 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
> initialization:
>
> class User < ActiveRecord::Base
>   encoded_field :encoded_stuff {
>     age => "23",
>     hair_color => "black",
>     eye_color => "brown"
>   }
> end

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 passwordmethod 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
encoded_data.

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 ... :)  But, that''s for another day.

--
Rick
rick.tessner-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org