[英]How to speed up Dynamic Select in Rails 4
I was able to create a dynamic dropdown list for Province and City by using an Adjacent list model that references to itself and jquery but it takes forever to load. 通过使用引用自身和jquery的相邻列表模型,我能够为Province和City创建一个动态下拉列表,但是要永久加载。
It works how I wanted it to work however; 它可以按我希望的方式工作。 this process takes 7473.4ms to load every time it renders the form since I have 1718 rows in my locations table and it tries to load all 1718 of them one at a time.
由于我的locations表中有1718行,并且每次尝试一次加载全部1718行,因此每次呈现表单时,此过程都要加载7473.4ms。
I found out that what's making it load longer is the grouped_collection_select but I can't think of a faster alternative for this. 我发现导致加载时间更长的是grouped_collection_select,但是我想不出更快的替代方法。 Is there a query tweak you can advise me to make this form load faster?
是否有查询调整项,您可以建议我加快此表单的加载速度?
The model looks like this: 该模型如下所示:
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"
end
and the db (locations table) looks something like this but it has 1718 rows: db(位置表)看起来像这样,但它有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
I was able to make the dynamic dropdown by using a "collection_select" for the provinces dropdown and a "grouped_collection_select" for the cities in my _form.html.haml: 我可以通过在_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"
then I used jQuery to show only the cities under the selected province in my js.cofee file: 然后我使用jQuery在js.cofee文件中仅显示所选省份以下的城市:
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()
I was able to lower down the speed by using preload in grouped_collection
: 我可以通过在
grouped_collection
使用preload来降低速度:
it preloads all child_locations which made the loading time faster 它会预加载所有child_locations,从而加快加载时间
= f.grouped_collection_select :location_id, Location.preload(:child_locations), :child_locations, :name, :id, :name, {prompt: "Select a City/Municipality"}, id: "city"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.