العضو (نموذج) التسلسل الهرمي، ذاتية المرجع الانضمام

StackOverflow https://stackoverflow.com/questions/1416983

  •  06-07-2019
  •  | 
  •  

سؤال

وأنا في محاولة لمعرفة كيفية الحصول على علاقة المستخدم مستويين.

والمصورين لدى العملاء. العملاء ومصور واحد. كلاهما المستخدمين.

ولقد حصلت على نموذج العضو الذي يبدو مثل هذا:

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 مجرد يعطيني مجموعة فارغة.

وماذا أفعل الخطأ؟

هل كانت مفيدة؟

المحلول

ويجب تبديل 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top