Rails: Many to many relation to self

允我心安 提交于 2021-02-08 05:42:07

问题


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:

Migration:

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

Association model:

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

回答1:


This should work:

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


来源:https://stackoverflow.com/questions/38577147/rails-many-to-many-relation-to-self

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