【发布时间】:2017-03-23 09:04:27
【问题描述】:
我正在创建一个基本的订阅应用程序,并且想知道对以下关系建模的最简洁的方法是什么。我似乎对has_and_belongs_to_many 关系以及何时使用它们感到困惑。
我正在尝试大致创建下面的结构,有几点需要注意。 subscription 和order 都只能有一个plan,但subscriptions 和orders 可以有很多products。
计划也以与产品相同的方式创建。即可以创建 6 个计划,然后可以将其添加到任意数量的订阅中(类似于产品)。
目前我有以下:
# User Model
has_one :subscription
has_one :plan, through: :subscription
# Subscription Model
belongs_to :user
belongs_to :plan # Not sure this is correct as a subscription should only be allowed to have 1 plan which belongs to the subscription.
# Plan Model
has_many :subscriptions # Again this doesn't feel quite right as I think the plan should belong to the subscription.
# Product Model
has_and_belongs_to_many :orders
has_and_belongs_to_many :subscriptions
# Order Model
belongs_to :user
has_and_belongs_to_many :products
任何人都可以就最佳建模方法提供任何建议,我们将不胜感激。
【问题讨论】:
-
当您编写表定义时,通常很清楚您需要什么关系。例如,如果您将
user_id添加到subscriptions,那么subscriptionbelongs_touser。 -
如果您无法将 foreign_id 添加到任何一个表中,则它是
has_and_belongs_to_many
标签: ruby-on-rails ruby activerecord model relationships