Rails 4 - 依赖选择导致错误的急切加载(Rails4 / Active Admin)

时间:2015-06-08 18:56:16

标签: javascript ruby-on-rails ruby-on-rails-4 activeadmin turbolinks

我有一个带有依赖选择的活动面板,即第一个下拉选择中的选项会影响第二个下拉列表中显示的内容。

几个月前一切都运转良好,但我刚刚意识到它已不再适用了。

我设法找到了导致错误的原因:如果我删除了预先加载(“include”),那么它又会再次运行。

不工作:(当前版本):

@deal_subsectors = DealSector.find(params[:deal_sector_id],
   include: :deal_subsectors).dealsubsectors

我收到此错误(表单是chrome dev工具的控制台)

GET http://localhost:3000/admin/deals/deal_subsectors_by_deal_sector?deal_sector_id=2 404 (Not Found)    
send @ jquery.js?body=1:9660    
jQuery.extend.ajax @ jquery.js?body=1:9211    
jQuery.(anonymous function) @ jquery.js?body=1:9357    
jQuery.extend.getJSON @ jquery.js?body=1:9340    
update_deal_subsector @ active_admin.js?body=1:19    
(anonymous function) @ active_admin.js?body=1:12    
jQuery.event.dispatch @ jquery.js?body=1:4666    
elemData.handle @ jquery.js?body=1:4334    
ListPicker._handleMouseUp @ about:blank:632

工作,当我删除“包含”/急切加载时

@deal_subsectors = DealSector.find(params[:deal_sector_id]).deal_subsectors

在这种情况下它完美无缺。

但我真的很想加载交易子部门,所以我想知道是什么导致了这个错误,自从它工作以来发生了什么变化。我有一些假设,但找不到罪魁祸首。

  • Rails 4改变了我应该使用find的方式(params [:id] ..)或者我应该使用预先加载的方式

  • 活跃的管理员改变了它处理预先加载的方式:也许它仅适用于索引,而不适用于编辑页面......

  • 现在Rails 4上的turbolinks改变了我必须加载的方式吗?

以下是代码:

- 在Active Admin

ActiveAdmin.register Deal do

# controller for the multi-select sector/subsector in the form
# does 2 things at same time: creates method and automatically defines the route of the method defined in controller
    if params[:deal_sector_id] # pass the id
      @deal_subsectors = DealSector.find(params[:deal_sector_id], include: :deal_subsectors).dealsubsectors
    else
      @deal_subsectors = []
    end

    render json: @deal_subsectors
  end   

end

- 具有2个相关选择的表单

form do |f|

f.inputs "Client" do


      f.input :deal_sector_id,
        :label      => "Select industry:",
        :as         => :select,
        :prompt     => true,
        :collection => DealSector.order("name").all.to_a
      f.input :deal_subsector_id,
        :label      => "Select subindustry:",
        :as         => :select,
        :prompt     => true,
        :collection => DealSubsector.order("name").all.to_a        
    end

end

- 支持它的javascript:

        // for edit page
        var deal_subsector = { };

       $(document).ready(function() {
         $('#deal_deal_sector_id').change(function() {
            update_deal_subsector();
         });
       });

       function update_deal_subsector() {
           deal_sector_id = $('#deal_deal_sector_id').val(); //get the value of sector id
           url = '/admin/deals/deal_subsectors_by_deal_sector?deal_sector_id=' + deal_sector_id; //make a query to the url passing the deal sector id as a parameter
          $.getJSON(url, function(deal_subsectors) {
              console.log(deal_subsectors);
                  $('#deal_deal_subsector_id').html("") //just blanks the id, blank it before populating it again if sector changes
              for( i = 0; i < deal_subsectors.length; i++) {
                 console.log(deal_subsectors[i]);
                 $('#deal_deal_subsector_id').append("<option value=" + deal_subsectors[i].id + ">" + deal_subsectors[i].name + "</option>")
      };
    }); //pass the url and function to get subsector ids and all we get is assigned to the variable subsector_id
  };

          // for index page (filters)
          $(document).ready(function() {
              $('#q_deal_sector_id').change(function() {
                 update_deal_subsector_filter();
              });
              });

          function update_deal_subsector_filter() {
               deal_sector_id = $('#q_deal_sector_id').val(); //get the value of sector id
               url = '/admin/deals/deal_subsectors_by_deal_sector?deal_sector_id=' + deal_sector_id; //make a query to the url passing the deal sector id as a parameter
               $.getJSON(url, function(deal_subsectors) {
                      console.log(deal_subsectors);
                $('#q_deal_subsector_id').html("") //just blanks the id, blank it before populating it again if sector changes
                 for( i = 0; i < deal_subsectors.length; i++) {
                     console.log(deal_subsectors[i]);
                     $('#q_deal_subsector_id').append("<option value=" + deal_subsectors[i].id + ">" + deal_subsectors[i].name + "</option>")
      };
    }); //pass the url and function to get subsector ids and all we get is assigned to the variable subsector_id
        };

已添加文件

class DealSector < ActiveRecord::Base
  has_many    :deal_subsectors
end

class DealSubsector < ActiveRecord::Base    
  belongs_to  :deal_sector,   :foreign_key => 'deal_sector_id'
end

3 个答案:

答案 0 :(得分:2)

当您致电ActiveRecord::find时 - 这意味着您希望从数据库中获得一个单一模型。 然后,您引用此模型并致电dealsubsectors - 我认为它与您的模型有has_many的关系。它将产生2个查询:首先获取原始DealSelector,第二个 - 所有相关DealSubsectors。 您无法优化(除非您dealsubsectors是模型中的自定义方法,而不是关系)。

如果您看到某些内容在您的数据库中出现问题 - 您必须在另一个地方查看。比如说,您的表单 - 每个表单只显示一个客户端吗?如果没有,它将为每个新客户端再次迭代并获取所有DealSector和DealSubsector。尝试提供更多代码。

答案 1 :(得分:1)

Rails 4附带了一些关于预先加载算法的更改。 您可以尝试以下代码片段:

@deal_subsectors = DealSector.eager_load(:deal_subsectors).find(params[:deal_sector_id]).dealsubsectors

@deal_subsectors = DealSector.includes(:deal_subsectors).find(params[:deal_sector_id]).dealsubsectors

第一个将在单个查询中获取数据,但第二个将进行两个查询。

答案 2 :(得分:0)

为什么您只能获取给定sector_id的所有DealSubsector记录?

DealSubsector.where(deal_sector_id: params[:deal_sector_id])