From STI, MTI or CTI, which is the current Rails 4 solution?

I have a base events table and you want to have sub-tables for each type of event ( hiking , party , riverrun , etc.).

I see a lot of old (2011/2012) posts about CTI, MTI and STI. Some solutions worked in Heroku, while others did not.

What is the β€œcurrent” Rails way of doing this type of thing? Was this added in Rails 4.x? Is there a magic stone that can handle this (using Postgres on Heroku)?

Some information if this helps:

In the future, there will be between 20-50 events, and each subcategory may consist of 80 columns. The site is hosted on Heroku. Running Rails 4.0.2

+7
inheritance ruby-on-rails postgresql ruby-on-rails-4 sti
source share
1 answer

STI - Inheriting from individual tables is what you are looking for. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html

You create your model as always, but you add the even_type attribute as a string to your database. (default ist "type") You let EventModel know that it will be an inheritance column.

 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 

Than you will create some subclasses. Make sure they inherit from Event

 class Party < Event end class UltraFestival < Event end class Tomorrowland < Event end 

In principle, all objects are events! Therefore, if you go to Event.all , you will get them all! Technically, an object may be something else. All these "Events" will be stored in one table, they will differ by event_type , which in this example will be "party", "ultra_festival" or "budland".

Now you can add some special materials for each of these classes, for example

  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 

This is the standard Rails path - over the years. Of course, it works on every hoster and with postgres.

// change: if your sub-events need some special tables in the database, then you need to go to MTI, multi-table-inheritance.

0
source share

All Articles