You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails ActiveRecord非等值关联查询性能优化及DOM ID问题求助

Rails部门资产追踪应用查询性能与DOM ID问题

应用背景

我们有一个用于跟踪部门资产注册(包括子网和IP地址)的Rails应用。Department模型与Subnet、Ip模型均为一对多关联,需展示两类核心数据:

  • 本部门在其他子网的IP(@dept_ips)
  • 其他部门在本部门子网上的IP(@others_ips)

模型代码

Department模型

class Department < ApplicationRecord
  
  has_many(:subnets, class_name: "Subnet", foreign_key: :department_id)
  has_many(:ips, class_name: "Ip", foreign_key: :department_id)
    ...
end

Subnet模型

通过自定义方法获取所属子网的IP地址:

class Subnet < ApplicationRecord
  def ips
    Ip.for_subnet(subnet)
  end
  ...
end

Ip模型

提供基于子网的IP查询类方法:

class Ip < ApplicationRecord
  def self.for_subnet(subnet)
    where("ip << '#{subnet.to_cidr}'")
  end
  ...
end

关联表信息

  • 已注册子网关联描述信息、防火墙信息等表;
  • 已注册IP关联主机名、敏感数据级别等表。

查询性能问题

加载@others_ips(其他部门在本部门子网上的IP)及关联信息的查询速度极慢,使用eager_load后性能有所提升,但索引页面加载仍未达到预期;而@dept_ips的加载速度正常。当前查询代码如下:

@others_ips 查询实现

@others_ips = @department.subnets
                          .eager_load(ips:[:calc_ip, 
                                           :host, 
                                           {subnet: :fw_subnet}] )
                          .order('ip.ip')
                          .map(&:ips)
                          .flatten

@dept_ips 查询实现

@dept_ips = @department.ips
                        .eager_load(:calc_ip,
                                    :host, 
                                    {subnet: :fw_subnet})
                        .order('ip.ip')

尝试方案的问题

尝试通过原生SQL结合服务类与实体类实现查询,功能正常但系统测试无法通过,原因是实体类没有dom_id,不知道如何为这类实体创建dom_id。

内容的提问来源于stack exchange,提问作者S Etling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:40:20