Gerarchia utente (modello), join autoreferenziale
-
06-07-2019 - |
Domanda
Sto cercando di capire come avere una relazione utente a due livelli.
I fotografi hanno clienti. I clienti hanno un fotografo. Entrambi sono utenti.
Ho un modello utente che assomiglia a questo:
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
E un modello di associazione che assomiglia a:
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
Quando lo riempio con alcuni dati e avvio la console, l'esecuzione di user.clients.all o user.photographer mi dà solo un array vuoto.
Cosa sto sbagliando?
Soluzione
Dovresti cambiare le 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow