首页 > 解决方案 > 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

在考虑该解决方案时需要一些帮助。

标签: ruby-on-rails

解决方案


只是一个快速提示 - 看看多态关联: https ://guides.rubyonrails.org/association_basics.html#polymorphic-associations

它的机制在股息表中放置了一个外键和一type列。该type列告诉您什么类型的记录是父记录 -stockreit.


推荐阅读