Ruby on rails 用户(模型)层次结构,自引用联接

Ruby on rails 用户(模型)层次结构,自引用联接,ruby-on-rails,hierarchy,Ruby On Rails,Hierarchy,我正试图找出如何建立两级用户关系 摄影师有客户。客户有一个摄影师。两者都是用户 我的用户模型如下所示: class User < ActiveRecord::Base #authlogic has_many :client_associations, :foreign_key => 'client_id', :class_name => 'Association', :dependent => :destroy has_man

我正试图找出如何建立两级用户关系

摄影师有客户。客户有一个摄影师。两者都是用户

我的用户模型如下所示:

class User < ActiveRecord::Base
  #authlogic

  has_many :client_associations, 
    :foreign_key => 'client_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_many :clients, :through => :client_associations

  has_one :photographer_association, 
    :foreign_key => 'photographer_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_one :photographer, :through => :photographer_association

end
class用户client\u id',
:class_name=>“关联”,
:dependent=>:destroy
拥有多个:客户端,:至=>:客户端\u关联
有一个:摄影师协会,
:foreign_key=>“摄影师id”,
:class_name=>“关联”,
:dependent=>:destroy
有一个:摄影师,:通过=>:摄影师协会
结束
以及一个如下所示的关联模型:

create_table "associations", :id => false, :force => true do |t|
    t.integer "photographer_id"
    t.integer "client_id"
end

class Association < ActiveRecord::Base
  belongs_to :client, :class_name => 'User'
  belongs_to :photographer, :class_name => 'User'
end
create_表“associations”,:id=>false,:force=>true do | t|
t、 整数“摄影师id”
t、 整数“客户端id”
结束
类关联'User'
属于:摄影师,:class\u name=>“用户”
结束
当我用一些数据填充它并启动控制台时,运行user.clients.all或user.摄影师只会给我一个空数组


我做错了什么?

您应该切换外键:

  has_many :client_associations, 
    :foreign_key => 'photographer_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_many :clients, :through => :client_associations

  has_one :photographer_association, 
    :foreign_key => 'client_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_one :photographer, :through => :photographer_association