导轨的has_many自我指涉 [英] Rails has_many self referential

查看:149
本文介绍了导轨的has_many自我指涉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下(简化)的账户模型:

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 目前工作正常,但我也希望能够访问 @ account.child_accounts - 我需要做什么才能做修复

@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?

推荐答案

我认为它是圆的另一种方式:

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

这篇关于导轨的has_many自我指涉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆