gpt4 book ai didi

ruby-on-rails - 如何加速 Rails 4 中的动态选择

转载 作者:行者123 更新时间:2023-11-29 13:27:52 25 4
gpt4 key购买 nike

我能够通过使用引用自身和 jquery 的相邻列表模型为省和市创建动态下拉列表,但它需要永远加载。

然而,它按照我希望的方式工作;每次呈现表单时,此过程需要 7473.4 毫秒来加载,因为我的位置表中有 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"
end

数据库(位置表)看起来像这样,但它有 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"

然后我使用 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()

最佳答案

我能够通过在 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"

关于ruby-on-rails - 如何加速 Rails 4 中的动态选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30282528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com