STI - Single Table Ereditarietà è quello che stai cercando. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html
È possibile creare il proprio modello come sempre, ma si aggiunge un attributo even_type
come stringa al database. (predefinito ist "tipo") Si lascia che EventModel sappia che questa sarà la colonna di ereditarietà.
class Event < ActiveRecord::Base
self.inheritance_column = :event_type
# dont forget your scopes to easy access them by type
# Event.party or Event.ultrafestival
scope :party, -> { where(event_type: 'Party') }
scope :ultrafestival, -> { where(event_type: 'UltraFestival') }
scope :tomorrowland, -> { where(event_type: 'TomorrowLand') }
def host
raise "needs to be implemented in your sub-class!"
end
end
Di creare alcune sottoclassi. Assicurarsi che quelli sono eredita da Event
class Party < Event
end
class UltraFestival < Event
end
class Tomorrowland < Event
end
In sostanza, tutti gli oggetti sono Eventi! Quindi se vai Event.all
li avrai tutti! Tecnicamente un oggetto può essere qualcos'altro. Tutti quegli "Eventi" saranno memorizzati nella stessa tabella, saranno differiti dal event_type
che sarà in questo esempio "party", "ultra_festival" o "tomorrowland".
Ora è possibile aggiungere un po 'roba speciale per ciascuna di tali classi, ad esempio
class Party < Event
def host
"private homeparty PTY"
end
def publish_photostream
end
def call_a_cleaning_woman
end
end
class UltraFestival < Event
attr_accessor :location
def host
"UMF Festival Corp."
end
def is_in_europe?
end
def is_in_asia?
end
end
class Tomorrowland < Event
def host
"ID&T"
end
def download_after_movie!
end
end
Questo è il modo standard di Rails - da anni. Ovviamente lavora su ogni hoster e con postgres.
// edit: se i tuoi eventi secondari necessitano di alcune tabelle speciali nel database, allora devi passare a MTI, multi-table-inheritance.
fonte
2015-08-19 18:41:02
forse dammi qualche feedbeck sulla mia risposta per farmi sapere se hai bisogno di ulteriore assistenza –