2017-07-11 13 views
0

私はレールモデルの関連付けを理解しようと悩み、私が使用するために必要なものの関連考え出すを抱えている:理解レールにhas_one has_manyのモデル団体

ここに私のアプリモデル

Company ---- Subscription ---- SubscriptionType

SubscriptionTypeです3種類のサブスクリプションとそれに関連する価格のリストがあります。

Company has_one :subscription

サブスクリプションはbelong_to :companyです。

また、他のフィールドを、持っているように最初に、私はSubscription has_one SubscriptionTypeSubscriptionType has_many Subscriptionsしかし、その関係は、私のsubscription_spec.rb

it { should have_one(:subscription_type) } 
で動作するようには思えないと考え

などtrial_start_datetrial_end_datecharge_date、など

しかし、これは私に、SubscriptionTypeテーブルに大量のレコードを残したくないので、この関係がうまくいかないことを示す次のエラーをもたらします。

Expected Subscription to have a has_one association called subscription_type (SubscriptionType does not have a subscription_id foreign key.) 

誰かが私の頭をこれで包んでくれるのを助けることができますか?

答えて

2

has_onebelongs_toの違いはすべて約where the foreign key livesです。

Subscription has_one :subscription_typeは、subscription_id列を持ち、Subscriptionにのみ属することを意味します。

Subscription belongs_to :subscription_typeSubscriptionsubscription_type_id列を持っており、SubscriptionTypeが複数のSubscription Sに属することができることを意味します。

は、だからあなたの質問に答えるために、ここでの正しい関係はあなたがこのような団体を設定することができます

class Subscription < ApplicationRecord 
    belongs_to :subscription_type 
end 

class SubscriptionType < ApplicationRecord 
    has_many :subscriptions 
end 
+0

これは実際には意味があります。おそらく、私はRoRのドキュメントをあまりにも長く読み込んでいたのですが、それはギリシャ語に変わり始めたからです)ありがとう! – Godzilla74

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) } 
+0

さらに詳しくおねがいします!アダムはマットに最初だったので、彼に信用を与えました...あなたの答えにいくつかの信憑性を加えました。 – Godzilla74