您可以在一个模型中使用多个自联接,就像下面的代码一样。我的协会的简要概述
模型
class User < ActiveRecord::Base
has_many :manager, class_name: "User", foreign_key: "admin_id"
belongs_to :admin, class_name: "User"
has_many :team_leader, class_name: "User", foreign_key: "manager_id"
belongs_to :manager, class_name: "User"
has_many :staff, class_name: "User", foreign_key: "team_leader_id"
belongs_to :team_leader, class_name: "User"
has_many :client, class_name: "User", foreign_key: "team_leader_id"
belongs_to :team_leader, class_name: "User"
has_and_belongs_to_many :client , class_name: "User", foreign_key: "client_id"
has_and_belongs_to_many :staff , class_name: "User", foreign_key: "staff_id"
end
和我的数据库表
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.integer :user_id
t.integer :admin_id
t.integer :manager_id
t.integer :team_leader_id
t.integer :staff_id
t.integer :client_id
t.timestamps null: false
end
end
end
任何帮助将不胜感激