首页 > 解决方案 > Rails:collection_select 带有多个嵌套关联的集合

问题描述

我对此一无所知:我有一个表单,您可以在其中选择服务端口正在侦听的 IP 地址。

<%= form.collection_select(:listener_id, Ipaddress.all, :id, :ipv4address, {include_blank: t("ports.select")}, { class: "form-control" }) %>

给定以下模型:

我想将“端口”与“IP 地址”连接起来。如您所见,在我的 collection_select 中,我创建了所有 IP 地址的集合。甚至来自其他系统或其他客户的。这不是我想要的。

在另一种情况下,我可以做类似的事情:Customer.find(System.find(@networkinterface.system.id).customer_id).systems.all,但我现在找不到如何做我的收藏的方法。我想列出该系统上所有可能的 IP 地址,或者来自客户的所有系统。

有人可以减轻我的负担吗?什么是最简单的,什么是最好的方法?

标签: ruby-on-railscollectionsassociations

解决方案


您在这里要做的是设置允许您遍历树的间接关联

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" }) %>

推荐阅读