[英]Ruby Rails find ip address in a range from low and high fields in db table
我有一個數據庫表,其中包含 7000 條記錄的低 IP 地址和高 IP 地址,並且我正在使用 Rails IPAaddr
類。
如果我的request.remote_ip
在表的low
或high
字段中找到,我會得到low
和high
並將它們從查詢中放入IPAddr
然后運行它,我得到一個true
。 現在我被問到,如果remote_ip
地址不存在於表中,但它屬於表中的低和高 ip 地址范圍,也得到一個true
。
任何想法都將受到高度贊賞。
它實際上相對簡單,Postgres 內置inet
類型:
Thing.where(
"inet ? << any(array[things.low, things.high]::inet[])", ip_address
)
這將測試傳遞的 ip 地址是否包含在上限和下限內。 inet
函數轉換為 inet 類型。 Ruby 等價物是:
IpAddr.new(low)..IpAddr.new(high).cover?(IpAddr.new(ip_address))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.