has_many: durch + polymorphe Beziehungen
-
29-09-2019 - |
Frage
ich mit rails3 und versuchen, einige komplexe Assoziationen zu bauen.
Ich habe Produkt, Version und Objektmodelle.
class Version < ActiveRecord::Base
belongs_to :product
has_many :specs
has_many :properties, :through => :specs
end
class Product < ActiveRecord::Base
has_many :versions
has_many :specs
has_many :properties, :through => :specs
end
class Property < ActiveRecord::Base
end
class Spec < ActiveRecord::Base
belongs_to :product
belongs_to :spec
belongs_to :version
end
Es funktioniert perfekt, aber ich will, Produkt und Version als polymorphe Beziehungen verwenden, so Tabelle Spezifikationen nur spec_id und some_other_id haben werden, statt spec_id, product_id, version_id.
ich kann nicht herausfinden, wo ich setzen soll: wie und wo: polymorphe => true. Können Sie mir helfen?
Lösung
Wie wäre:
class Version < ActiveRecord::Base
belongs_to :product
has_many :specs, :as => :speccable
has_many :properties, :through => :specs
end
class Product < ActiveRecord::Base
has_many :versions
has_many :specs, :as => :speccable
has_many :properties, :through => :specs
end
class Property < ActiveRecord::Base
end
class Spec < ActiveRecord::Base
belongs_to :speccable, :polymorphic => true
belongs_to :spec
end
#table: specs(id,spec_id,speccable_type,speccable_id)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow