Reputation: 2497
I have a simple rails app where I am trying to establish the relationship between two models.
I have a plan model and a subscription model.
A subscription will only ever have 1 plan but plans can belong to many subscriptions.
As there is no belong to many relationship I am guessing that the best way to create this is using has_and_belongs_to_many with a join table of plan_subscription - is this correct?
Assuming this is correct how do I ensure that my subscription only ever has a single plan created?
The current code I have is as follows:
class Subscription < ApplicationRecord
has_and_belongs_to_many :plans
end
class Plan < ApplicationRecord
has_and_belongs_to_many :subscriptions
end
Any help would be much appreciated.
Upvotes: 0
Views: 41
Reputation: 556
has_and_belongs_to_many association is many to many association and you wrote subscription will only ever have 1 plan, plans can belong to many subscriptions so in this case your association is wrong.Your association will be like this:
class Plan < ActiveRecord::Base
has_many :subscriptions
end
class Subscription < ActiveRecord::Base
belongs_to :plan
end
Upvotes: 3