代码之家  ›  专栏  ›  技术社区  ›  Ryan Florence

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

  •  0
  • Ryan Florence  · 技术社区  · 15 年前

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

    我做错了什么?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Roger Ertesvag    15 年前

    您应该切换外键:

      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