1

我有三张桌子父母,孩子和资金。

父.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

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

4

2 回答 2

0

您在这里不需要连接表 - 而是子记录上的父 ID 列。所以,在你的情况下:

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

has_and_belongs_to_many仅当您实施orhas_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 %>

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

于 2018-06-12T15:30:23.793 回答
0

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

父.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的参考链接

于 2018-06-12T15:49:07.587 回答