Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many self referential

I have an accounts model as follows (simplified):

class Account < ActiveRecord::Base
    attr_accessible :account_number, :display_name, :master_account_id

    has_many :child_accounts, :class_name => "Account", :foreign_key => "id"
    belongs_to :master_account, :class_name => "Account", :foreign_key => "master_account_id"
end

@account.master_account is currently working correctly, but I also want to be able to access @account.child_accounts - what do I need to do in order to fix that?

like image 870
bdx Avatar asked Jan 17 '23 08:01

bdx


1 Answers

I think it has to be the other way round:

class Account < ActiveRecord::Base
  has_many :child_accounts, :class_name => "Account", :foreign_key => "master_account_id"
  belongs_to :master_account, :class_name => "Account"
end
like image 161
Stefan Avatar answered Jan 31 '23 08:01

Stefan