Question

J'essaie de comprendre comment établir une relation utilisateur à deux niveaux.

Les photographes ont des clients. Les clients ont un photographe. Les deux sont des utilisateurs.

J'ai un modèle d'utilisateur qui ressemble à ceci:

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

Et un modèle d'association ressemblant à:

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

Lorsque je le remplis avec des données et que je lance la console, l'exécution de user.clients.all ou de user.photographer me donne simplement un tableau vide.

Qu'est-ce que je fais de travers?

Était-ce utile?

La solution

Vous devriez changer les 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top