0

对于单表继承,如何强制 Rails 使用整数列作为“类型”列而不是字符串?

4

2 回答 2

1

您可以覆盖 Rails 用来将表名转换为类名的方法,反之亦然:

相关方法find_sti_class负责将存储在类型列中的值转换为相应的 ActiveRecord 模型,sti_name并负责在给定 ActiveRecord 子类的情况下检索存储在类型列中的值。

您可以像这样覆盖它们:

class Institution::Base < ActiveRecord::Base

  ALLOWED_CLASSES = %w[Institution::NonProfit Institution::Commercial]

  class << self

    def find_sti_class type_name
      idx = type_name.to_i
      super if idx == 0
      ALLOWED_CLASSES[idx-1].constantize
    rescue NameError, TypeError
      super
    end

    def sti_name
      idx = ALLOWED_CLASSES.index(self.name)
      if idx.nil?
        super
      else
        idx + 1
      end
    end

  end

end

我写了一篇文章更详细地阐述了这一点。

于 2015-12-01T16:42:08.143 回答
0

您必须找到 ActiveRecord 负责处理“类型”列的部分并对其进行修补,即覆盖它在您的应用程序中的工作方式。

于 2009-07-09T15:11:32.630 回答