سؤال

لدي ثلاثة نماذج ، كل منها لديه الجمعيات التالية:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end

كما ترون في النص المعلق ، لقد ذكرت ما أحتاجه.

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

المحلول

يمكنك فقط إنشاء الطريقة للوصول إليها

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

أو يمكنك تفويض طريقة Model1

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end

نصائح أخرى

لماذا لا تحاول:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
 belongs_to :model1
 has_many   :model3s, :primary_key => :model1_id,
                      :foreign_key => :model1_id

end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many   :model2s, :primary_key => :model1_id,  
                       :foreign_key => :model1_id
end

سيكون لهذا السجل النشط JOIND SOMM2 و Model3 بواسطة Model1_ID LING MODEL1 منه تمامًا ويجب أن يكون أكثر كفاءة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top