关系数据库 table 可能与其他 table 有关系也可能没有关系

Relational database table that may or may not have relationship with other table

在我的 rails 应用程序中,有两个 tables PlanSubscriptionPlan table 有 has_manySubscriptionSubscriptionbelongs_toPlan

我想创建一个不属于 PlanSubscription。我可以在不指定 plan_id 的情况下创建 Subscription 吗?或者,我应该使用 has_many_through?

是的,您可以在不指定 Plan 的情况下创建 Subscription。如果你在 Rails 5,你需要做:

belongs_to :plan, optional: true

根据 docs:

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false.

我个人不太喜欢 rails 中的默认要求 belongs_to 5. 您可以在 application.rb 中添加此行。如果需要 belongs_to,则必须添加验证。

config.active_record.belongs_to_required_by_default = false