我能够通过使用一个引用自身和jquery的相邻列表模型来创建一个省和市的动态下拉列表,但它需要很长时间才能加载。
但是,它的工作方式是我想要的;这个过程每次呈现表单都需要7473.4ms来加载,因为我的locations表中有1718行,并且它试图一次加载所有的1718行。
我发现让它加载时间更长的是grouped_collection_select,但我想不出一个更快的替代方案。有没有一个查询调整你可以建议我让这个表单加载更快?
该模型如下所示:
class Location < ActiveRecord::Base
has_many :books
belongs_to :parent_location, class_name: Location
has_many :child_locations, class_name: Location, foreign_key: "parent_id"
enddb (位置表)看起来像这样,但它有1718行:
id location parent_id
1 Philippines
2 Metro Manila 1
3 Abra 1
4 Caloocan City 2
5 City of Las Pinas 2
6 Pilar 3
7 Sallapadan 3我可以通过在我的_form.html.haml中为省份下拉列表使用"collection_select“,为城市使用"grouped_collection_select”来创建动态下拉列表:
= f.collection_select :location_id, Location.where(parent_id: "1"), :id, :name, {prompt: "Select a Province"}, id: "province"
= f.grouped_collection_select :location_id, Location.all, :child_locations, :name, :id, :name, {prompt: "Select a City/Municipality"}, id: "city"然后在我的js.cofee文件中使用jQuery仅显示所选省份下的城市:
jQuery ->
city = $('#city').html()
$('#province').change->
province = $('#province :selected').text()
options = $(city).filter("optgroup[label='#{province}']").html()
if options
$('#city').html(options)
else
$('#city').empty()发布于 2015-05-17 11:44:44
我可以通过在grouped_collection中使用预加载来降低速度
它预先加载了所有的child_locations,这使得加载时间更快
= f.grouped_collection_select :location_id, Location.preload(:child_locations), :child_locations, :name, :id, :name, {prompt: "Select a City/Municipality"}, id: "city"https://stackoverflow.com/questions/30282528
复制相似问题