我试图理解一个rails模型关联,并且无法弄清楚我需要使用哪种关联:
这是我的应用模型
Company ---- Subscription ---- SubscriptionType
SubscriptionType有3种不同类型的订阅及其相关价格的列表。
A Company has_one :subscription
。
订阅将belong_to :company
。
它还有其他字段,例如trial_start_date
,trial_end_date
,charge_date
等。
起初,我认为Subscription has_one SubscriptionType
和SubscriptionType has_many Subscriptions
但这种关系似乎不适用于我的subscription_spec.rb
it { should have_one(:subscription_type) }
但是这给了我以下错误,这表明这种关系不起作用,因为我不想在SubscriptionType表中有大量的记录:
Expected Subscription to have a has_one association called subscription_type (SubscriptionType does not have a subscription_id foreign key.)
有人可以帮助我解决这个问题吗?
答案 0 :(得分:2)
has_one
与belongs_to
之间的区别仅为where the foreign key lives。
Subscription has_one :subscription_type
表示SubscriptionType
有一个subscription_id
列,只属于一个Subscription
。
Subscription belongs_to :subscription_type
表示Subscription
有subscription_type_id
列,SubscriptionType
可以属于多个Subscription
。
所以回答你的问题,这里的正确关系是
class Subscription < ApplicationRecord
belongs_to :subscription_type
end
class SubscriptionType < ApplicationRecord
has_many :subscriptions
end
答案 1 :(得分:1)
您可以设置如下关联:
class Company < ApplicationRecord
has_one :subscription
end
# subscriptions table should have columns company_id and subscription_type_id
class Subscription < ApplicationRecord
belongs_to :company
belongs_to :subscription_type
end
class SubscriptionType < ApplicationRecord
has_many :subscriptions
end
通过此设置,可以将关联的对象访问为:
company = Company.find(1)
# to get subscription object with company_id: 1
company.subscription
# to get subscription_type object of the company's associated subscription
company.subscription.subscription_type
# to get all subscriptions of a particular subscription_type
SubscriptionType.last.subscriptions
然后,您的subscription_spec.rb
看起来像:
it { should belong_to(:company) }
it { should belong_to(:subscription_type) }