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:

  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!

require 'ipaddr'

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

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

HTH
- 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:

http://ruby-doc.org/stdlib/libdoc/ipaddr/rdoc/classes/IPAddr.html

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}
  end

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

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

end

Hope this helps.

-=nathan