Skip to content

Instantly share code, notes, and snippets.

@plusor
Last active December 16, 2015 23:39
Show Gist options
  • Save plusor/5515700 to your computer and use it in GitHub Desktop.
Save plusor/5515700 to your computer and use it in GitHub Desktop.
If you have only one area column in the table, and you want searches .
class Area < ActiveRecord::Base
acts_as_nested_set :counter_cache => :children_count
#Area.rebot(省ID,[市ID])
#Area.rebot(3198,[3213]) or Area.rebot(3198)
scope :robot, ->(s,q=[]) { where("parent_id in (?)",q.or(select(:id).where(:parent_id => s))) }
[:parent,:root,:province,:city,:district].each do |instance|
class_eval <<-EOF,__FILE__,__LINE__ + 1
delegate :name,:to => :#{instance} ,:allow_nil => true,:prefix => true
#{next if [:parent].include?(instance)}
delegate :id ,:to => :#{instance} ,:allow_nil => true,:prefix => true
EOF
end
def province
root
end
def city
parent_id == root_id ? self : (parent || opstruct)
end
#主要用户判断是否为区
def district
parent_id == city_id ? self : opstruct
end
def cities
province.children
end
def districts
city.children
end
private
def opstruct(int_id=SecureRandom.hex(6),int_name="")
OpenStruct.new(:id => int_id,:name => int_name)
end
end
require 'active_support/core_ext/object/blank'
class Object
def or(other)
blank? ? other : self
end
end
class UsersController < ApplicationController
def index
province_id,city_id,area_id = params[:province_id].or(nil),params[:city_id].or(nil),params[:area_id].or(nil)
if area_id.present?
params[:search][:userarea_id_eq] = area_id
elsif province_id.present?
params[:search][:userarea_id_in] = Area.robot(province_id,[city_id].compact).map(&:id)
end
#You need before install meta_search
@search = User.search(params[:search])
@users = @search
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment