Rails:与自我的多对多关系 [英] Rails: Many to many relation to self

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

问题描述

我在创建此关联时遇到问题:考虑模型条目".我希望条目有许多条目作为父条目,我希望条目有许多条目作为子条目.我想通过一个我称为关联"的模型来实现这种关系,所以这是我尝试的:

I am having problems creating this association: Consider a model "Entry". I want entries to have many entries as parents and I want entries to have many entries as children. I want to realize this relation via a model I called "Association", so here is what I tried:

迁移:

class CreateAssociations < ActiveRecord::Migration[5.0]
  def change
    create_table :associations do |t|
      t.integer :parent_id
      t.integer :child_id
    end
  end
end

关联模型:

class Association < ApplicationRecord
  belongs_to :parent, class_name: 'Entry'
  belongs_to :child, class_name: 'Entry'
end

到目前为止它有效.但是现在我如何使用它在一个模型上创建两个多对多关系?

so far it works. But now how do I use this to create two many-to-many relations on a model to itself?

class Entry < ApplicationRecord
  # has many parent entries of type entry via table associations and child_id
  # has many child entries of type entry via table associations and parent_id
end

推荐答案

这应该有效:

class Entry < ApplicationRecord
  has_and_belongs_to_many :parents, class_name: 'Entry', join_table: :associations, foreign_key: :child_id, association_foreign_key: :parent_id
  has_and_belongs_to_many :children, class_name: 'Entry', join_table: :associations, foreign_key: :parent_id, association_foreign_key: :child_id
end

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

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