2014-06-17 16 views
7

Ho una tabella di base events e desidero avere tabelle secondarie per ogni tipo di evento (hiking, party, , ecc.).Di STI, MTI o CTI, che è la soluzione Rails 4 attualmente suggerita?

Vedo molti vecchi post (2011/2012) relativi a CTI, MTI e STI. Alcune soluzioni funzionavano per Heroku, mentre altre no.

Qual è il modo "corrente" di eseguire questo tipo di cose? È stato aggiunto a Rails 4.x? C'è una gemma magica che gestisce questo (con Postgres su Heroku)?

Alcune informazioni se aiuta:

In futuro, ci sarà tra 20-50 eventi, e ogni sotto-tabella potrebbe essere fino a 80 colonne. Il sito è ospitato su Heroku. Running Rails 4.0.2

+0

forse dammi qualche feedbeck sulla mia risposta per farmi sapere se hai bisogno di ulteriore assistenza –

risposta

0

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.