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