关于javascript:筛选选择列表之间的信息

Filter information between selection lists

我正在尝试建立一个人们可以投票的网站。在注册部分,人们可以选择他们的城市和state,但是我真正想要做的是使用来自SQLite数据库的信息根据state对城市进行过滤。这是我在程序中调用选择列表的方式:

1
2
<%= f.label"Ciudad:" %>
<%= f.select :ciudade_id, grouped_options_for_select(Departamento.order(:nombre).map{ |group| [group.nombre, group.ciudades.map{ |ciudade| [ciudade.nombre, ciudade.id] } ] }), { prompt: true}, {:onchange => 'populate(this.id, 'puesto_id')'}, required: true, class: ' order_form ciudades_search'%>

项目外观如下:

状态选择。

enter


如果要通过AJAX访问Rails数据库中的state/城市信息,则需要创建一条路线和控制器以提供该信息。

但是SQLite并不会真正削减它-它不是为大型生产数据库而构建的,并且没有像ILIKE这样的搜索功能。我会推荐Postgres。

1
resources :states, only: [:show, :index]
1
2
3
4
5
6
7
class State < ActiveRecord::Base
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :state
end
1
2
3
4
5
6
7
8
9
10
11
12
13
class StatesController < ApplicationController
  # GET /states(.json)
  def index
    @states = State.all
    @states = State.where("name ILIKE ?", params[:search]) if params[:search]
    render json: @states
  end
  # GET /states/:id(.json)
  def show
    @state = State.includes(:cities).find(params[:id])
    render json: @state, include: :cities
  end
end

然后可以将其与Select2之类的东西一起使用或推出自己的解决方案。

但是,如果您要创建一个全局应用程序,则可能要使用http://www.geonames.org/之类的服务,因为保持最新的全局数据库会很疯狂。