简体   繁体   中英

Rails : has_one and belongs_to same model

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM