我如何拥有同一模型的多个实例? [英] How can I has_and_belongs_to_many multiple instances of the same model?

查看:35
本文介绍了我如何拥有同一模型的多个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想完成这样的事情:

Basically, I want to accomplish something like this:

Class Node < ActiveRecord::Base
  has_and_belongs_to_many :parents, :class_name=>'Node'
  has_and_belongs_to_many :children, :class_name=>'Node'
end

但它不起作用,我不完全确定这样做的正确方法.接下来我将尝试明确定义一个连接表并让两者都使用它:如果这是解决方案,该列会被称为children_id"还是child_id"?

but it isn't working, and I'm not entirely sure the proper way to do this. I'm going to try explicitly defining a join table next and have both use it: If that's the solution, would the column be called "children_id" or "child_id"?

推荐答案

这是可行的,但我强烈建议使用 has_many :through 代替:

This is doable, but I strongly recommend using has_many :through instead:

class Node < ActiveRecord::Base
  has_many :parent_node_links,
    :class_name => 'NodeLink',
    :foreign_key => :child_id

  has_many :parents,
    :through => :parent_node_links,
    :source => :parent

  has_many :child_node_links,
    :class_name => 'NodeLink',
    :foreign_key => :parent_id

  has_many :children,
    :through => :child_node_links,
    :source => :child
end

class NodeLink < ActiveRecord::Base
  belongs_to :parent,
    :class_name => "Node"
  belongs_to :child,
    :class_name => "Node"
end

拥有一流的连接模型可以更轻松地管理关系,并让您可以在以后自由添加相关元数据.

Having a first-class join model makes it much easier to manage the relationships and gives you the freedom to add relevant meta-data at a later point in time.

这篇关于我如何拥有同一模型的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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