【问题标题】:Single Table Inheritance not working in Rails 4 app - ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed单表继承在 Rails 4 应用程序中不起作用 - ActiveRecord::SubclassNotFound:单表继承机制失败
【发布时间】:2014-10-09 14:36:09
【问题描述】:

我有一个新的 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.

这里发生了什么?我做错了什么?

提前致谢。

【问题讨论】:

  • Remote class 你看起来怎么样?
  • 远程类
  • 你为什么要花这么多精力自己操作类型列? Rails 将完全为您处理...

标签: ruby-on-rails ruby activerecord single-table-inheritance


【解决方案1】:

为了调试这个,我想看看我从两个实验之一中学到了什么......

首先,即使只是暂时的,将子类移出 Orders 文件夹。可能是您将它们嵌套在模块中,或者 rails 期望它们基于名称,因此“类型”列与您认为的不匹配。

其次,我会尝试从命令行创建一个子类,将其持久化,然后查看 ActiveRecord 在该类型列中放入的内容,看看它是否符合您的预期。

我怀疑这与模型下的子文件夹有关,并且 Rails 无法找到类型指定的类。

【讨论】:

    【解决方案2】:

    列名“类型”在 ActiveRecord 中受到限制。尝试将列名重命名为其他名称,或者如果您无法尝试:

    self.inheritance_column = :_type_disabled
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多