ruby-on-rails - Rails 5对不同的表使用belongs_to和条件
问题描述
我正在开发一个带有不同表和关联的 Rails 应用程序,并试图找到最好的解决方案,但还不知道。
一个表/类称为类别
例如
Categories
- Stocks
- Reits
-(...)
每个类别一张表
Stocks
belongs_to :category
Reits
belongs_to :category
比我想创建一个名为“股息”的表,有一个条件,不知道是否可能,例如:
Dividends
belongs_to :category
if category_id == 1
belongs_to :stock
end
if category_id == 2
belongs_to :reit
end
使用命令:
rails g scaffold dividends category:references stock:references reit:references
但我不知道这是否会令人困惑,如果可能会更好地为每个类创建一个表,例如:
StocksDividends
belongs_to :category
belongs_to :stock
ReitsDividends
belongs_to :category
belongs_to :reit
在考虑该解决方案时需要一些帮助。
解决方案
只是一个快速提示 - 看看多态关联: https ://guides.rubyonrails.org/association_basics.html#polymorphic-associations
它的机制在股息表中放置了一个外键和一type
列。该type
列告诉您什么类型的记录是父记录 -stock
或reit
.
推荐阅读
- azure - Azure DevOps:获取 Git 存储库的管理员和贡献者
- python - OSError: [WinError 127] 找不到指定的程序
- java - 在两个地图中乘以对应值的最佳方法
- javascript - 无法用硒点击的对象
- python - ValueError:列的长度必须与 get_dummies 的键长度相同
- python - 'href' 之后的起搏文本
- docker - Github 主机密钥验证失败
- cgo - cgo 从 *type 转换为 *void
- java - 如何在不清除用户输入的情况下清除 Java 中的控制台
- python - 随机选择列表中的元素,但有例外