簡體   English   中英

單表繼承在Rails 4 app中不起作用 - ActiveRecord :: SubclassNotFound:單表繼承機制失敗

[英]Single Table Inheritance not working in Rails 4 app - ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed

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

這里發生了什么? 我做錯了什么?

提前致謝。

為了調試這個,我只是簡單地看看我從兩個實驗中學到的東西......

首先,即使只是暫時的,也要將子類移出Orders文件夾。 可能是您將它們嵌套在模塊中,或者軌道期望它們基於名稱,因此“類型”列與您認為應該匹配的列不匹配。

第二,我嘗試從命令行創建一個子類,持久化它,並查看ActiveRecord在該類型列中放置的內容,看它是否與您期望的相匹配。

我懷疑這與模型下的子文件夾有關,而Rails無法在類型指定的情況下找到類。

當我使用type作為列名時,我有同樣的問題,也許嘗試將列名重命名為其他名稱?

列名'type'在ActiveRecord中受到限制。 嘗試將列名重命名為其他內容,或者如果您無法嘗試:

self.inheritance_column = :_type_disabled

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM