我使用rails 3.2.3,ruby 1.9.3和postgres 8.4.12(在RHEL 6.3上)。我希望将IP地址存储为数据库中的整数,但在尝试从控制器保存记录时会出现以下错误:
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
我收到以下错误
PG::Error: ERROR: value "4294967040" is out of range for type integer
我的迁移将此列定义为8字节整数:
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
但是我能够在rails控制台上存储这个大整数:
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
那么,这个bigint数据类型是否应该在其他地方定义?提前谢谢。
答案 0 :(得分:4)
如果升级到PG 9.1,则可以使用其原生IP address/Subnet/MAC address types。您甚至可以使用postgres_ext gem在迁移中使用它们。这应该自动处理任何类型的IP地址,而不必将它们转换为BIGINT或STRING,并允许一些很棒的技巧,例如“SELECT FROM * IN SAME SUBNET”