【问题标题】:Table Associations in Ruby on RailsRuby on Rails 中的表关联
【发布时间】:2013-05-27 02:20:06
【问题描述】:

有两个表,groups 和 groups_hierarchy。 groups 有关于组的标准信息,group_hierarchy 有两列(父、子),列出父组的 id 和子组的 id。这就是说子组是父组的子组。我一直试图弄清楚 GroupHierarchy 和 Group Data Models 中的关联是什么。有人可以帮我解决这个问题吗?

一个组可以有许多子组,也可以是许多其他组的子组。我认为这将是 Group 中的 has_many :grouphierarchies 和 GroupHierarchy 中的 belongs_to :group 但这不起作用......问题是 GroupHierarchy 在技术上属于 2 个组。

谢谢

【问题讨论】:

  • 双向自引用 Has-and-belongs-to-many 关系可以在这里工作。见ruby-forum.com/topic/119583
  • 感谢您的信息,我无法使用它,但至少它是一个开始
  • 没关系,我确实可以使用您发布的内容...我只是为了修复我在其他课程中遇到的错误。所以谢谢你。
  • 太棒了!请在下面发布您的答案,以便它可以帮助其他人。带代码的答案比我只带链接的答案要好。

标签: ruby-on-rails associations hierarchy bidirectional self-reference


【解决方案1】:

在我的组模型中,我需要以下内容:

class Group < ActiveRecord::Base

has_and_belongs_to_many :children, :class_name => 'Group', :join_table => 'groups_hierarchy', :foreign_key => 'parent', :association_foreign_key => 'child'

has_and_belongs_to_many :parents, :class_name => 'Group', :join_table => 'group_hierarchy', :foreign_key => 'child', :association_foreign_key => 'parent'

结束

而且您实际上不需要 GroupHierarchy 类中的任何内容,它似乎只是充当支持表以允许自引用。

再次感谢

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多