欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

如何在rails项目中实现省市县三级联动

1.首先在数据库中建三张表,provinces, cities, towns.表间关系都是一对多。

2.需要写一个脚本,向三张表中添加省市县的数据。

    在model中新建一个文件,tool.rb.添加: 

class Tool < ActiveRecord::Base
  def self.init_province_city_and_town
    require 'httparty'
    # 定义URL
    url = "http://www.helloweba.com/demo/cityselect/js/city.js"
    response = HTTParty.get url
    #puts "======== #{response.body} ==========="
    # 获取 到结果
    items = JSON.parse(response.body) rescue []
    Province.transaction do
      return if items.blank?
      items['citylist'].each do |province|
        province_name = province['p']
        @province = Province.create :name => province_name
        Rails.logger.info "province ==!!!!==!!!!!== #{province_name}"
        next if province['c'].blank?    
        City.transaction do    
          province['c'].each do |city|    
            city_name = city['n']           
            @city = City.create :name => city_name, :province_id => @province.id
            Rails.logger.info "city ======== #{city_name}"
            next if city['a'].blank?        
            Town.transaction do
              city['a'].each do |town|        
                town_name= town['s']            
                @town = Town.create :name => town_name, :city_id => @city.id 
                Rails.logger.info "town ======== #{town_name}"
              end              
            end                
          end                  
        end                    
      end                      
    end
  end
end

在rails console中输入:

Tool.init_province_city_and_town

这样省市县就都初始化成功了。

3.接下来就开始实现三级联动。  在app/assets/javascript/province_city_town.js  设置一个全局的js,全局使用三级联动。

$( document ).ready(function() {
    $("#manager_province_id").change(function () {
        if ($(this).val()) {
            get_cities_by_province_id($(this).val());
        }
    });

    $("#manager_city_id").change(function () {
        if ($(this).val()) {
            get_towns_by_city_id($(this).val());
        }
    });

    function get_cities_by_province_id(province_id) {
        $.ajax({
            type: 'get',
            url: '/users/get_cities_by_province_id?province_id=' + province_id,
            success: function (data) {
                $("#manager_city_id").html(data);
            },
            error: function () {
                alert("fail!");
            }
        });
    }

    function get_towns_by_city_id(city_id) {
        $.ajax({
            type: 'get',
            url: '/users/get_towns_by_city_id?city_id=' + city_id,
            success: function (data) {
                $("#manager_town_id").html(data);
            },
            error: function () {
                alert("fail!");
            }
        });
    }
});

4.在app/controllers/users_controller 中添加方法:

 
def get_cities_by_province_id
  @cities = City.where(:province_id => params[:province_id])
  render :layout => false
end
    
def get_towns_by_city_id     
  @towns = Town.where(:city_id => params[:city_id])
  render :layout => false    
end

5.在对应的 views/users/get_cities_by_province_id.html.erb  ,views/users/get_towns_by_city_id.html.erb中分别添加:

<%= options_from_collection_for_select @cities, :id, :name  %>

<%= options_from_collection_for_select @towns, :id, :name  %>

6.在需要三级联动的view 页面,添加:

<%= f.select :province_id, options_from_collection_for_select(Province.all, :id, :name), {:include_blank=>"请选择省份"}, :style => "width: 115px;"%>
<%= f.select :province_id, options_from_collection_for_select([], :id, :name), {:include_blank=>"请选择城市"}, :style => "margin-left: 20px; width: 115px;"%>
<%= f.select :province_id, options_from_collection_for_select([], :id, :name), {:include_blank=>"请选择乡镇"}, :style => "margin-left: 20px; width: 115px;" %>

省市县三级联动就完成了

 

返回列表