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地址。

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

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

您要在此处进行的设置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" }) %>
本文链接:https://www.f2er.com/3001094.html

大家都在问