我如何使用 postgresql 在 Rails 4 中对 IP 地址进行排序

Kas*_*ail 1 sorting postgresql ruby-on-rails ip-address

我的 postgresql 表中有“ip”列,其中包含 ip 地址。我想按升序对这些 ip 地址进行排序。下面以数据为例

    147.226.211.40
    1.39.80.12
    128.237.199.43
Run Code Online (Sandbox Code Playgroud)

结果应该是

    1.39.80.12
    128.237.199.43
    147.226.211.40
Run Code Online (Sandbox Code Playgroud)

换句话说,如果 ip 地址是 abcd,则按 a、b、c 和 d 排序。

这在模型中对我不起作用。

  default_scope { order('ip ASC') }
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Mik*_*ll' 5

PostgreSQL 支持 inet 数据类型。使用正确的数据类型,许多问题就会消失。

scratch=# create table test (
scratch(# ip_addr inet not null);
CREATE TABLE
scratch=# insert into test values ('147.226.211.40');
INSERT 0 1
scratch=# insert into test values ('1.39.80.12');
INSERT 0 1
scratch=# insert into test values ('128.237.199.43');
INSERT 0 1
scratch=# select * from test order by ip_addr;
Run Code Online (Sandbox Code Playgroud)
    ip_addr     
----------------
 1.39.80.12
 128.237.199.43
 147.226.211.40
(3 行)

ActiveRecord支持 inet 数据类型。简单来说 。. .

$ bin/rails generate scaffold IpAddr ip_addr:inet 
Run Code Online (Sandbox Code Playgroud)

编辑控制器。按符号排序:ip_addr

$ head -9 app/controllers/ip_addrs_controller.rb 
class IpAddrsController < ApplicationController
  before_action :set_ip_addr, only: [:show, :edit, :update, :destroy]

  # GET /ip_addrs
  # GET /ip_addrs.json
  def index
    @ip_addrs = IpAddr.all.order(:ip_addr)
    #                      ^^^^^^^^^^^^^^^
  end
Run Code Online (Sandbox Code Playgroud)

浏览到该页面,您将找到正确排序的 IP 地址。