Sirch
Sirch

Reputation: 417

How to handle large integers in Rails 3 and postgres

Im using rails 3.2.3, ruby 1.9.3, and postgres 8.4.12 (on RHEL 6.3). I was hoping to store IP addresses as integers in a database, but get the following error when trying to save the record from the controller:

  def create
    @network = Network.new(params[:network])

    @network.address_int = IPAddr.new(@network.address_str).to_i
    @network.netmask_int = IPAddr.new(@network.netmask_str).to_i

    respond_to do |format|
      if @network.save
        format.html { redirect_to @network, notice: 'Network was successfully created.' }
        format.json { render json: @network, status: :created, location: @network }
      else
        format.html { render action: "new" }
        format.json { render json: @network.errors, status: :unprocessable_entity }
      end
    end
  end

I get the following error

PG::Error: ERROR:  value "4294967040" is out of range for type integer

My migration defines this column as a 8 byte integer:

class CreateNetworks < ActiveRecord::Migration
  def change
    create_table :networks do |t|
      t.integer :vlan
      t.integer :address_int, :limit => 8      
      t.integer :netmask_int, :limit => 8
      t.string :address_str
      t.string :netmask_str
      t.string :desc

      t.timestamps
    end
  end
end

But I have been able to store this large integer at the rails console:

1.9.3p125 :001 > n=Network.new
 => #<Network id: nil, vlan: nil, address_int: nil, address_str: nil, netmask_int: nil, netmask_str: nil, desc: nil, created_at: nil, updated_at: nil>
1.9.3p125 :002 > n.address_int=4294967040
 => 4294967040
1.9.3p125 :003 > n
 => #<Network id: nil, vlan: nil, address_int: 4294967040, address_str: nil, netmask_int: nil, netmask_str: nil, desc: nil, created_at: nil, updated_at: nil>
1.9.3p125 :004 > n.save
(0.2ms)  BEGIN
  SQL (5.0ms)  INSERT INTO "networks" ("address_int", "address_str", "created_at", "desc", "netmask_int", "netmask_str", "updated_at", "vlan") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["address_int", 4294967040], ["address_str", nil], ["created_at", Tue, 10 Jul 2012 15:09:37 UTC +00:00], ["desc", nil], ["netmask_int", nil], ["netmask_str", nil], ["updated_at", Tue, 10 Jul 2012 15:09:37 UTC +00:00], ["vlan", nil]]
(0.9ms)  COMMIT
 => true

So, should this bigint data type be defined somewhere else too? Thanks in advance.

Upvotes: 3

Views: 1997

Answers (1)

thoughtpunch
thoughtpunch

Reputation: 1937

If you upgrade to PG 9.1 you can use their native IP address/Subnet/MAC address types. You can even use them in your migrations with the postgres_ext gem. This should automatically handle IP address of any type without having to cast them as BIGINT or STRING and allow some awesome tricks such as "SELECT FROM * IN SAME SUBNET"

Upvotes: 4

Related Questions