简体   繁体   中英

Rails Single Table Inheritance

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

You can override the methods Rails uses to convert the table name to class name and vice versa:

The relevant methods are find_sti_class which is responsible for the translating the value stored in the type column to the respective ActiveRecord model and sti_name which is responsible for retriving the value stored in type column given an ActiveRecord subclass.

You can override them like this:

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

I have written a post elaborating this in more detail.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM