Rails:具有多个嵌套关联的集合的collection_select

问题描述 投票:0回答:1

我对此一无所知:我有一个表格,您可以在其中选择服务端口正在侦听的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地址的列表。

有人可以照亮我吗?什么是最简单的方法,什么是最好的方法?

ruby-on-rails collections associations
1个回答
0
投票

您要在此处执行的设置是indirect associations,可让您遍历树:

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" }) %>
© www.soinside.com 2019 - 2024. All rights reserved.