I am trying store IP addresses in a database. In my old PHP days when I
wrote the SQL i used the INET_ATON and INET_NTOA functions in MySQL to
to the conversions of the address when I inserted or pulled the rows
from the database. I would like to do something similar with my
ActiveRecord model in Rails as storing the IP as an integer is much more
efficient than in its dot format.
My question is how do I do it? Is there a way for me to setup my model
so that whenever it saves it converts the stored IP and when it finds a
record it automatically converts it back to the dot format? Is there a
way I can use the MySQL functions? Or could I just always keep it in
the integer state, but have accessors in the class convert it when I
access it?
My question is how do I do it? Is there a way for me to setup my model
so that whenever it saves it converts the stored IP and when it finds a
record it automatically converts it back to the dot format? Is there a
way I can use the MySQL functions? Or could I just always keep it in
the integer state, but have accessors in the class convert it when I
access it?
Yow, no. Wait, yes. You could use a activerecord callback for
before_save to change the IP before writing to the database:
The table that I will be using will be getting large (a similar system
we have right now is growing at about 1 million records a month) and
using 4 bytes instead of 15 will really add up over time. (Yes, I know
how cheap storage is nowadays, but I would like to avoid the adventure
of a full drives as long as possible, been there done that!)
I was looking to see if there was a way if I could mimic the “serialize”
functionality, but I’m afraid I am going to have to study ActiveRecord a
lot more first.
Peer
Matthew B. wrote:
On Fri, 2007-06-01 at 22:47 +0200, Peer A. wrote:
My question is how do I do it? Is there a way for me to setup my model
so that whenever it saves it converts the stored IP and when it finds a
record it automatically converts it back to the dot format? Is there a
way I can use the MySQL functions? Or could I just always keep it in
the integer state, but have accessors in the class convert it when I
access it?
Yow, no. Wait, yes. You could use a activerecord callback for
before_save to change the IP before writing to the database: