Encoded Columns and ActiveRecord

Yow, no. Wait, yes. You could use a activerecord callback for
before_save to change the IP before writing to the database:


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'

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!

require 'ipaddr'

IPAddr.new("").to_i # => 3232235530

IPAddr.new(3232235530, Socket::AF_INET).to_s # => ""

- H

Hi Peer,

You can store the IP as an integer in the database and convert to and
from a string using Ruby. Check out this class:


This seems to work:

class Address < ActiveRecord::Base

  require 'IPAddr'

  def self.find_by_ip(value)
    find :first, :conditions => {:ip => IPAddr.new(value).to_i}

  # Convert from integer - IPAddr doesn't seem to have this method
  def ip
    [read_attribute(:ip)].pack("N").unpack("C*").join "."

  def ip=(value)
    write_attribute(:ip, IPAddr.new(value).to_i)


Hope this helps.