Re: Encoded Columns and ActiveRecord

Matthew Beale
Fri, 01 Jun 2007 21:04:52 -0000

On Fri, 2007-06-01 at 22:47 +0200, Peer Allan 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:

  http://railsmanual.com/module/ActiveRecord::Callbacks

but there is no callback for retrieval. Ahha, but we can just overwrite
the method in the model:

  def ip
    self.ip.gsub /2/, ''3''
  end

Would replace 2s with 3s.

But really, why not just store it as a string? Why do you want to store
it as a number? It isn''t a number, it''s an IP.

Good luck!

--
Matthew Beale :: 607 227 0871
Resume & Portfolio @ http://madhatted.com