单表继承在 Rails 4 应用程序中不起作用 - ActiveRecord::SubclassNotFound:单表继



我有一个新的Rails 4应用程序,我在STI配置中创建了几个模型。

主模型称为Order,它继承自ActiveRecord::Base。这是它的样子:

class Order < ActiveRecord::Base
  TYPES = %w(remote local)
  scope :remotes,  -> { where(type: 'remote') }
  scope :locals,   -> { where(type: 'local') }
end

另外两个模型位于models/orders的一个文件夹中,它们称为 RemoteLocal,它们都继承自Order

订单迁移文件如下所示:

def change
  create_table :orders do |t|
    t.string :source_url, null: false
    t.string :final_url, null: false
    t.string :type
    t.string :category
    t.timestamps
  end
end

我还确保我将models/orders目录包含在 Rails 中,方法是执行以下操作:

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]

现在,当我使用清空的数据库登录控制台并运行Order.all一切都很好,我得到一个空的关系对象。但是在我创建第一个Remote对象并尝试再次运行Order.all后,我收到以下错误:

>> Order.all
Order Load (1.0ms)  SELECT "orders".* FROM "orders"
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate
the subclass: 'Remote'. This error is raised because the column 'type' is reserved
for storing the class in case of inheritance. Please rename this column if you didn't
intend it to be used for storing the inheritance class or overwrite
Order.inheritance_column to use another column for that information.

这是怎么回事?我做错了什么?

提前谢谢。

为了调试这个,我只是简单地看看我从两个实验中的一个中学到了什么......

首先,即使只是暂时,也要将子类移出"订单"文件夹。可能是你把它们嵌套在一个模块中,或者 rails 希望它们基于名称,所以"类型"列与你认为的不匹配。

其次,我会尝试从命令行创建一个子类,持久化它,并查看 ActiveRecord 在该类型列中放置的内容,看看它是否与您期望的匹配。

我怀疑这与模型下的子文件夹以及 Rails 无法找到该类有关,因为类型正在指定它。

列名称"类型"在活动记录中受到限制。 尝试将列名称重命名为其他名称,或者如果您不能尝试此操作:

self.inheritance_column = :_type_disabled

当我使用 type 作为列名时,我遇到了同样的问题,也许尝试将您的列名重命名为其他名称?

最新更新