在三个表之间的导轨中连接



我有三个表父母,孩子和资金。

parent.rb

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

儿童.rb

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

资金.rb

class Funding < ApplicationRecord
belongs_to :child
end

儿童和基金之间的结合

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

孩子和父母之间的加入

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

子表有parent_id,资金表有child_id。如何在父项和资金表之间创建联接。请帮忙

此处不需要联接表 - 而是子记录上的父 ID 列。因此,在您的情况下:

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

联接表仅在实现has_and_belongs_to_manyhas_many through关系时发挥作用。

如果您考虑如何将记录绑定在一起,那么要使子项属于父项,子项只需要知道它与哪个父项相关联,因此需要知道列。

现在,假设父母有很多孩子,孩子有很多父母:单父母 ID 不会削减它,所以连接表进来将两者联系在一起,例如,在每行数据中包含(例如(parent_idchild_id

数据库使用这些方法将记录绑定在一起,根据需要查询 id 或联接表。

要从父记录访问资金,您可以将两者链接在一起(如果它们独立相关(,或者如果不是,则通过子记录访问。

对于后者,您可以使用如下所示的内容。

在控制器中:

@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 %>

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

如果您需要从父级获得资金,则可以在 Rails 中使用 has_many 和声明,如下所示:

parent.rb

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

儿童.rb

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

资金.rb

class Funding < ApplicationRecord
belongs_to :child
end

您可以通过@parent.fundings的父访问资金记录

这是has_many的参考链接