用户(模型)层次结构,自引用连接

时间:2009-09-13 06:06:43

标签: ruby-on-rails hierarchy

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

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

我有一个看起来像这样的用户模型:

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

一个看似如下的协会模型:

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

当我填充一些数据并启动控制台时,运行user.clients.all或user.photographer只会给我一个空数组。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你应该切换foreign_keys:

  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