Rails : has_one and belongs_to same model

53 views Asked by At

Say an admin can be the owner of an account and an account can have many admins. You would have association like the followings :

class Account < ApplicationRecord
   belongs_to :account_owner, foreign_key: :account_owner_id, class_name: 'Administrator', optional: true
   has_many :administrators
end

class Administrator < ApplicationRecord
 # account instance has an account_owner_id that references the administrator "app owner"
 has_one :account
 # administrator has an account_id on it that references the account he belongs_to
 belongs_to :account

That code doesnt work properly because the instance method account defined twice on Administrator clash with each other.

Then I would tend to writte something like this :

class Administrator < ApplicationRecord
  has_one :account, as: :proprietary_account
  belongs_to :account

to differentiate between the two "sides" of the association. However this doesnt work either and method proprietary_account is not created

Is there a way to model that with rails associations ? If not how would you create this kind of relationship in a rails app.

1

There are 1 answers

0
tanner2379 On

You need to create another table called admin_accounts and use the has_many :through association. The admin_accounts table will have two columns, one with admin_id, and one with account_id. You can then associate the two models through that table. More information here: https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association