首页 > 解决方案 > Rails:如何根据表 A 中的每条记录显示表 B 中的所有关联记录

问题描述

我有两个表 A 和 B。A 包含日期,B 包含描述以及 A_id 列。表 A 和 B 具有一对多关联。

Table A
---------------
id  | datecol
----+----------
1   |   03/01/2019
2   |   02/01/2019
3   |   01/01/2019 


Table B

id   |  description    |  A_id
-----+-----------------+------      
1    |  GK1_02/02/2019 | 2
2    |  GK3_01/01/2019 | 3
3    |  GK2_01/01/2019 | 3
4    |  GK1_01/01/2019 | 3
5    |  GK1_01/01/2019 | 1   

在我的 rails 模板中,我想显示如下条目:

01/01/2019 
 . GK1_01/01/2019

02/01/2019
 . GK1_02/02/2019

03/01/2019
 . GK1_02/02/2019
 . GK2_02/02/2019
 . GK3_02/02/2019

所以基本上,我想为 A 中的每个条目显示 B 中的所有关联记录。

有人可以协助我实施吗?

标签: ruby-on-railsruby-on-rails-5.2

解决方案


你所拥有的是一对多的关系。您可以使用 Active Record 关联https://guides.rubyonrails.org/association_basics.html来实现它。

例如,您的表 A 可能是 Author 模型,而您的表 B 可能是 Book 模型

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end

所以你的控制器可以搜索你的作者

class CatalogController < ApplicationController
  def list
    @authors = Author.all
  end
end

在您看来,迭代作者及其书籍(A.datecol 作为 Author.name,B.description 作为 Book.title )

<ul>
  <% @authors.each do |author| %>
    <li><span><%= author.name %></span>
      <ul>
        <% author.books.each do |book| %>
          <li><%= book.title %></li>
        <% end %>
      </ul>
    </li>
  <% end %>
</ul>

推荐阅读