ruby-on-rails - Rails:collection_select 带有多个嵌套关联的集合
问题描述
我对此一无所知:我有一个表单,您可以在其中选择服务端口正在侦听的 IP 地址。
<%= form.collection_select(:listener_id, Ipaddress.all, :id, :ipv4address, {include_blank: t("ports.select")}, { class: "form-control" }) %>
给定以下模型:
- 客户有很多系统
- 系统有许多网络接口
- 网络接口有许多 IP 地址
- 系统有很多服务
- 服务有很多端口
- 系统有许多网络接口
我想将“端口”与“IP 地址”连接起来。如您所见,在我的 collection_select 中,我创建了所有 IP 地址的集合。甚至来自其他系统或其他客户的。这不是我想要的。
在另一种情况下,我可以做类似的事情:Customer.find(System.find(@networkinterface.system.id).customer_id).systems.all
,但我现在找不到如何做我的收藏的方法。我想列出该系统上所有可能的 IP 地址,或者来自客户的所有系统。
有人可以减轻我的负担吗?什么是最简单的,什么是最好的方法?
解决方案
您在这里要做的是设置允许您遍历树的间接关联:
class Customer
has_many :systems
has_many :networkinterfaces, though: :systems
has_many :ipaddresses, through: :networkinterfaces
end
class Networkinterface
belongs_to :system
has_one :customer, through: :system
end
给定一个客户@customer
,您可以使用间接关联来获取 IP 地址列表。
<%= form.collection_select(:listener_id, @customer.ipaddresses, :id, :ipv4address, {include_blank: t("ports.select")}, { class: "form-control" }) %>
推荐阅读
- tensorflow - 使用 Tensorflow 对象检测 API 在 Faster R-CNN 中可视化来自 RPN 头部的提议区域
- onvif - Onvif TranslationSpaceFov 平移空间是否需要通过转换 x,y 坐标来使相机视图居中
- javascript - PowerBI JS SDK - setFilters() 从过滤器面板中删除除第一个过滤器之外的所有过滤器
- node.js - 将 system.profile 与猫鼬一起使用
- c# - Xamarin UWP + Android ContentPage 导航 PushAsync
- list - 带有小部件列表的 Flutter 动画切换器
- java - 您如何与 Android Studio 中的第三方通知进行交互?
- javascript - 在移相器 3 中绘制移动线
- flutter - 我可以在不打开 Flutter 应用的情况下收到分享意图吗?
- gcc - 在 CMake 中启用 UB 清理的惯用方式是什么?