ruby-on-rails - 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 中的所有关联记录。
有人可以协助我实施吗?
解决方案
你所拥有的是一对多的关系。您可以使用 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>
推荐阅读
- python - 在 Docker 中使用 pip install 获取自签名证书错误,但仅适用于某些软件包
- vba - 在插入之前运行插入后访问数据库
- bluetooth - 解码蓝牙 4.0 设备的 hcitool info 扩展功能的含义
- angular - 角材料表不显示任何数据
- javascript - Node.js Multer“.array 不是函数”
- airflow - 气流本地执行程序未运行 Dags
- java - 如何创建没有此错误的包?
- android - 如何在两个活动之间发送数据
- android-studio - 如何在android中使用按钮关闭应用程序
- hyperledger-fabric - 无法下载最新的超级账本结构二进制文件