Question

I'm in the process of building a back-end admin panel for our customers.

I'm integrating a feature to allow users to upgrade and downgrade their monthly subscription which means adding a new model for the billing_plans table.

I'm stuck trying to get the relationship right between an account and a plan.

I have a billing_plan model:

class BillingPlan < ActiveRecord::Base
  self.table_name = "billing_plans"
  has_many :accounts, primary_key: 'name', foreign_key: 'audio_billing_model'
end

and an accounts model:

class Account
  has_many :contacts
  belongs_to :user, primary_key: :email, foreign_key: :billing_email_address
  has_one :billing_plan, foreign_key: 'name', primary_key: 'audio_billing_model'
end

I'm sure this could help other people and I'm pretty certain someone must have come across it before.

Was it helpful?

Solution

Since you're trying to establish a has_many belongs_to relationship, simply define the primary key on the has_many model, then direct the belongs_to model to utilize that primary key as its foreign key:

# app/models/billing_plan.rb
class BillingPlan < ActiveRecord::Base
    self.table_name = "billing_plans" # Seems unnecessary, as the table name by default is `billing_plans`
    has_many :accounts, primary_key: 'name'
end

# app/models/account.rb
class Account < ActiveRecord::Base # Remember to subclass `ActiveRecord::Base`
  has_many :contacts
  belongs_to :user, primary_key: :email, foreign_key: :billing_email_address
  has_one :billing_plan, foreign_key: 'name'
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top