Rails 一个地区字段的小工具类

wootaw · 2017年02月16日 · 最后由 wootaw 回复于 2017年02月17日 · 1485 次阅读

看到社区里有人问地区字段的处理,想到我们项目里用到一个小工具类,还挺方便的,贡献出来,大家轻拍。

  • 地区用一个表存储(districts),只有两个字段:name,code
  • code 表示地区代码,2 位表示省/直辖市,4 位表示市,6 位表示区/县
  • 需要关联地区的表中都有一个 district_code 字段

然后有一个 Concern:

module Districtable

  extend ActiveSupport::Concern

  included do

    def descendant_and_self_districts
      District.where("code LIKE ?", "#{district_code}%")
    end

    def descendant_districts
      descendant_and_self_districts.order(:code).offset(1)
    end

    def children_districts
      District.where("code LIKE ?", "#{district_code}__")
    end

    def ancestor_and_self_districts
      District.where("? ~ code", district_code)
    end

    def ancestor_districts(start=1)
      ancestor_and_self_districts.order("code DESC").offset(start)
    end

    def parent_district
      ancestor_districts.take
    end

    def sibling_districts
      District.where("code LIKE ?", "#{district_code[0..-3]}__")
    end

    def district_name(split='')
      district_code.nil? ? nil : ancestor_and_self_districts.order(:code).map(&:name).join(split)
    end

  end

end

使用的时候,在关联地区的 Model 中

class Organization < ActiveRecord::Base
  include Districtable
end

如果有 districts 表的数据就更好了

@w7938940

我们用的数据是从腾讯微博设置个人信息页面上抓的,数据正好符合我们的表结构 districts

而最新的数据在这个问题下面的回复里。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号