Festlegen eines: has_many: durch die Verbindung auf einem belongs_to Verein Ruby on Rails
-
27-09-2019 - |
Frage
Ich habe drei Modelle, die jeweils die folgenden Verbände mit:
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
Wie Sie im kommentierten Text sehen kann, habe ich erwähnt, was ich brauche.
Lösung
Sie legen nur die Methode für den Zugriff it
class Model2 < ActiveRecord::Base
belongs_to :model1
def model3s
model1.model3s
end
end
Alternativ können Sie delegieren die model3s Methode model1
class Model2 < ActiveRecord::Base
belongs_to :model1
delegate :model3s, :to => :model1
end
Andere Tipps
Warum nicht versuchen:
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
Dies wird sich aktiv Rekord beitreten model2 und model3 von model1_id model1 Verlassen der es vollständig aus und sollte effizienter sein.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow