0

我试图弄清楚如何建立两级用户关系。

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

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

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 只会给我一个空数组。

我究竟做错了什么?

4

1 回答 1

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
于 2009-09-13T08:20:09.803 回答