在三个表之间加入 rails

Joins in rails between three tables

我有三个 table parents、children 和资金。

parent.rb

class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
end

child.rb

class Parent < ApplicationRecord
  belongs_to :parent
  has_many :fundings, dependent: :destroy
end

funding.rb

class Funding < ApplicationRecord
      belongs_to :child
end

加入 children 和资助

create_table "children_fundings", id: false, force: :cascade do |t|
    t.integer "child_id", null: false
    t.integer "funding_id", null: false
    t.index ["child_id", "funding_id"], name: 
    "index_children_fundings_on_child_id_and_funding_id"
    t.index ["funding_id", "child_id"], name: 
    "index_children_fundings_on_funding_id_and_child_id"
end

加入 children 和 parents

  create_table "children_parents", id: false, force: :cascade do |t|
    t.integer "parent_id", null: false
    t.integer "child_id", null: false
    t.index ["child_id", "parent_id"], name: 
    "index_children_parents_on_child_id_and_parent_id"
    t.index ["parent_id", "child_id"], name: 
    "index_children_parents_on_parent_id_and_child_id"
  end

childrentable有parent_id,资金table有child_id。如何在 parents children 和资金 table 之间创建连接。请帮助

您不需要在此处加入 tables - 而是 child 记录上的 parent ID 列。所以,在你的情况下:

  • Child 需要整数列 parent_id
  • Funding 需要整数列 child_id

加入 table 仅在您实施 has_and_belongs_to_manyhas_many through 关系时发挥作用。

如果您考虑如何将记录联系在一起,对于 child 属于 parent,child 只需要知道它属于哪个 parent绑定到,因此列。

现在,假设 parents 有很多 children,children 有很多 parents:一个 parent ID 不会削减它,因此连接 table 将两者联系在一起,在每行数据中包含(例如)parent_idchild_id

数据库使用这些方法将记录联系在一起,根据需要查询 ID 或加入 table。

要从 parent 记录访问资金,如果两者独立相关,您可以 link 一起访问,如果不是,则通过 children 访问。

对于后者,你可以使用类似下面的东西。

在你的控制器中:

@parents = Parent.includes(children: :fundings) # includes preloads the data, avoiding expensive N + 1 queries

在您看来:

<% @parents.each do |parent| %>
  <#% whatever you want to display regarding the parent here %>

  <% parent.children.each do |child| %>
    <#% whatever you want to display regarding the child here %>

    <% child.fundings.each do |funding| %>
      <#% whatever you want to display regarding the funding here %>
    <% end %>
  <% end %>
<% end %>

这有点乱,所以值得将控制器或部分中的数据分开。希望这能让您了解如何工作?

如果您需要从 parent 获得资金,您可以使用 has_many 通过 rails 中的声明,如下所示:

parent.rb

class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
  has_many :fundings, through: :children
end

child.rb

class Child < ApplicationRecord
  belongs_to :parent
  has_many :fundings, dependent: :destroy
end

funding.rb

class Funding < ApplicationRecord
  belongs_to :child
end

您可以通过 parent 使用 @parent.fundings

访问资金记录

这里是 link has_many through

的参考