Search code examples
ruby-on-railspostgresqlcidr

receive all matching networks for IP address from postgres db


I have a postgres db with a table networks which includes a column network of type cidr. I want to queue all networks which contain an IP address I provide. I couldnt find how to do this.

Currently I pull all networks, and then use the include? method IPAddr class provides:

Network.all.each{|row| pp row if row.network.include?("10.176.0.5")}

Solution

  • You can use postgres' >>= operator (includes or equal) or >>(includes) that is defined for cidr type:

    Network.where(['network >> ?', "10.176.0.5"])