Rails has_many self referential

社会主义新天地 提交于 2019-12-21 02:45:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/11100091/rails-has-many-self-referential

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!