ruby-on-rails – STI,MTI或CTI,这是目前建议的Rails 4解决方案
我有一个基本事件表,并希望为每个事件类型(远足,派对,河流等)提供子表.
我看到很多关于CTI,MTI和STI的旧帖子(2011/2012).一些解决方案适用于Heroku,而其他解决方案则没有. 什么是“当前”Rails做这种事情的方式?是否已将其添加到Rails 4.x中?是否有一个神奇的宝石处理这个(与Heroku上的Postgres)? 一些信息,如果它有帮助: 将来,将有20-50个事件,每个子表可能多达80列.该网站托管在Heroku上.运行Rails 4.0.2 解决方法
STI – 单表继承是您正在寻找的.
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html 您可以像往常一样创建模型,但是将属性even_type作为字符串添加到数据库中. (默认为“类型”) 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 比你创建一些子类.确保它们继承自Event class Party < Event end class UltraFestival < Event end class Tomorrowland < Event end 基本上,所有对象都是事件!所以如果你去Event.all,你会得到它们!从技术上讲,对象可以是其他东西.所有这些“事件”将存储在同一个表中,它们将与event_type不同,event_type将在此示例中为“party”,“ultra_festival”或“tomorrowland”. 现在,您可以为每个类添加一些特殊内容 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 这是标准的Rails方式 – 多年以来.当然它在每个主持人和postgres上工作. //编辑:如果您的子事件需要数据库中的某些特殊表,那么您需要进行MTI,多表继承. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |