开发者

How to do create IP address range

Is there any way to create IP address range? like 192.168.0.1/24. It's too annoy to create a data each time. I find a Rubygems' ipaddress. http://rubygems.org/gems/ipaddress. I would like to take this to created IP range.

in new.heml.erb

<%= f.lable :iprange %>
<%= f.text.field :iprange %>

I don't how do used it in the rails' models

ip = IPAddress("192.168.0.1/24")
ip.each do |i|
 p i.to_s
end

Somebody can give me some gui开发者_开发技巧de.


Is this what you are looking for? (Warning: untested):

Model: subnet.rb

require 'ipaddress'
class Subnet < ActiveRecord::Base
  has_many :addresses

  after_create :populate_addresses

  def populate_addresses
    range     = IPAddress(self.iprange)
    subnet_id = self.id

    range.each do |ip|
      Address.create(:ipv4 => ip, :subnet_id => subnet_id)
    end
  end
end

Model: address.rb

class Address < ActiveRecord::Base
  # ipv4: string
  # subnet_id: integer
  belongs_to :subnet
end

This probably isn't the ideal way of handling this - a bit more logic is probably necessary to handle updates to the Subnet model & cascade those changes to the Address model.

Anyway, I hope this helps a bit.


the best solution would be to provide a wrapper function in your model:

def iprange_arr
  IPAddress(iprange)
end

do not try to replace addresses in field (iprange) as it would be hard to read them back into view

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜