Qual è un buon design per un modello intermedio a tripla relazione?
-
08-07-2019 - |
Domanda
Sono nuovo su Rails e non afferro ancora tutte le possibilità con le associazioni. Ecco il mio problema:
Ho un paio di modelli come mela e limone. Poi c'è il modello "relazione" che contiene le triple delle relazioni:
soggetto | relazione | oggetto
mela | è più dolce di | limone
La migrazione per "relazioni" è questa:
create_table :relations do |t| t.references :subject, :polymorphic => true t.string :relation t.references :object, :polymorphic => true t.timestamps end
questo dovrebbe archiviare relazioni come
subject_id = 1
subject_type = apple
relazione = è più dolce di
object_id = 2
tipo_oggetto = limone
In realtà ho più di solo 2 modelli, quindi ho pensato di dover rendere il soggetto e la colonna del modello agnostici usando l'opzione polimorfica.
Come definiresti le associazioni nelle classi modello di mela, limone e relazione? Il design delle relazioni tra i tavoli è così buono?
Grazie mille per il tuo aiuto !!
-Alex
Soluzione
Fornisci lo schema db che hai descritto, sembra che dovrebbe essere abbastanza semplice:
class Relation < ActiveRecord::Base
belongs_to :object, :polymorphic => true
belongs_to :subject, :polymorphic => true
end
E le altre tue classi sembrerebbero così
class Apple < ActiveRecord::Base
has_many :object_relations, :class_name => 'Relation', :as => :object
has_many :subject_relations, :class_name => 'Relation', :as => :subject
end
class Orange < ActiveRecord::Base
has_many :object_relations, :class_name => 'Relation', :as => :object
has_many :subject_relations, :class_name => 'Relation', :as => :subject
end
Altri suggerimenti
POLIMORFO È DOLORE:
A meno che non sia necessario, utilizzare qualcosa come Ereditarietà a tabella singola:
class Fruit < ActiveRecord::Base
has_many :relations
has_many :related_objects, :through => :relation, :class_name => 'Fruit'
has_many :relating_subjects, :through => :relation, :class_name => 'Relation'
end
class Relation < ActiveRecord::Base
belongs_to :object, :class => 'Fruit'
belongs_to :subject, , :class => 'Fruit'
validate_presence_of :object_id
validate_presence_of :subject_id
validate_presence_of :relation
end
E poi come:
class Apple < Fruit
...
end
Spero che sia d'aiuto, (non ho testato questo codice)