Rails有很多自我指涉

时间:2012-06-19 11:34:10

标签: ruby-on-rails-3 associations

我有一个帐户模型如下(简化):

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目前正常运作,但我也希望能够访问@account.child_accounts - 我需要做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:9)

我认为必须采取相反的方式:

class Account < ActiveRecord::Base
  has_many :child_accounts, :class_name => "Account", :foreign_key => "master_account_id"
  belongs_to :master_account, :class_name => "Account"
end