Re: Encoded Columns and ActiveRecord

Nathan Amick
Sat, 02 Jun 2007 15:04:52 -0000

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