gpt4 book ai didi

ruby-on-rails - 单表继承在 Rails 4 应用程序中不起作用 - ActiveRecord::SubclassNotFound:单表继承机制失败

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:02 25 4
gpt4 key购买 nike

我有一个新的 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,它们都继承自 顺序

订单迁移文件如下所示:

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.

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

提前致谢。

最佳答案

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

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

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

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

关于ruby-on-rails - 单表继承在 Rails 4 应用程序中不起作用 - ActiveRecord::SubclassNotFound:单表继承机制失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com