单表继承在Rails 4 app中不起作用 - ActiveRecord :: SubclassNotFound:单表继承机制失败

时间:2014-02-09 09:36:50

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

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

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

提前致谢。

3 个答案:

答案 0 :(得分:3)

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

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

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

我怀疑这与模型下的子文件夹有关,而Rails无法在类型指定的情况下找到该类。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

列名'type'在ActiveRecord中受到限制。尝试将列名重命名为其他名称,或者如果你不能尝试这个:

self.inheritance_column = :_type_disabled