连接三个表之间的rails

时间:2018-06-12 15:27:19

标签: ruby-on-rails ruby join ruby-on-rails-5 jquery-datatables-rails

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

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

加入儿童与资金之间

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。如何在父母子女和资助表之间创建联接。请帮忙

2 个答案:

答案 0 :(得分:0)

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

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

只有在您实施has_and_belongs_to_manyhas_many through关系时,加入表才会发挥作用。

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

现在,想象父母有很多孩子,孩子有很多父母:单亲ID不会削减它,所以连接表将两者绑在一起,包含(例如)两个{{1}在每行数据中都有parent_id

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

要从父记录中获取资金,您可以将两者联系起来,如果他们是独立相关的,或者通过孩子访问,如果没有。

对于后者,您可以使用以下内容。

在您的控制器中:

child_id

在您看来:

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

这有点混乱,所以将控制器中的数据或部分数据分开是值得的。希望能让你知道如何使用它吗?

答案 1 :(得分:0)

如果您需要从父母那里获取资金,您可以使用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.fundings

通过家长访问资金记录

此处是has_many through

的参考链接
相关问题