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

标签 ruby-on-rails postgresql ruby-on-rails-4

我能够通过使用引用自身和 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/

相关文章:

ruby-on-rails - 具有自定义 View 的路线

ruby-on-rails - Rails 3.1.1 测试 :benchmark on Ruby 1. 9.3

ruby-on-rails - Rails 路由,:as option also changes the params hash . ..如何覆盖它?

sql - 使用大量 if-else 语句和 JSONification 简化 PL/pgSQL 函数

ruby-on-rails - 尝试升级到 Rails 5 时,出现 "Bundler could not find compatible versions for gem "railties""错误

sql - Ruby on Rails find_by 不区分大小写

postgresql - 如何使用 ServiceStack OrmLite 从插入返回标识值 - PostgreSQL

sql - 如何绑定(bind)数组参数以在 Postgres 中使用 IN 运算符进行过滤

ruby-on-rails - 将局部变量向下传递 Rails 4 中的部分层次结构以实现 Ransack 关联

ruby - 我如何在 ruby​​ 中解析这个 JSON