Rails : 如何根据 table A 中的每条记录显示来自 table B 中的所有关联记录

Rails : How to display all the associated records from table B based on every records from table A

我有两个 tableA 和 B。A 包含日期,B 包含描述以及 A_id 列。 table 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 中的所有关联记录。

有人可以帮助我实现它吗?

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

来实现它

例如,您的 table A 可以是 Author 模型,您的 table 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>