【问题标题】:Rails: Invalid single-table inheritance type errorRails:无效的单表继承类型错误
【发布时间】:2013-08-14 22:27:15
【问题描述】:

所以,我正在使用无法转换到 Rails 的现有数据库迁移这个 php 站点。有一个表:Quotes,其中有一列名为 type。每当我尝试创建此模型并设置类型时,它都会告诉我以下错误:

ActiveRecord::SubclassNotFound (Invalid single-table inheritance type: HOME is not a subclass of Quotes)

我不明白为什么它认为它是继承的,因为它不应该这样。我的创建方法如下所示:

quote = Quotes.create(
  agent_id: agent.id,
  client_id: client.id,
  type: 'HOME',
  status: 0,
  date_created: DateTime.now 
)

如果我注释掉类型,一切正常。但是使用类型它会出错。

【问题讨论】:

    标签: ruby-on-rails-4 rails-models


    【解决方案1】:

    我通过将模型继承列设置为 nil 解决了这个问题。 Active Record 模型可以通过:type 属性从表继承,将inheritance_column 设置为nil 会删除该属性,从而允许您拥有一个名为type 的数据库列

    class Quote < ActiveRecord::Base
        self.inheritance_column = nil
    end
    

    【讨论】:

    • 谢谢,这为我指明了正确的方向。我有一个名为“type”的列,它导致了错误。
    【解决方案2】:

    我讨厌代码深处有潜在的陷阱,尤其是在生成模型等初始过程中。如果需要,最好将保留字更改为其他内容,然后腾出时间来利用继承列。此处列出了更清洁的解决方案 -> rename a database column name using migration

    上面写着;

    1. 执行 $> rails 生成迁移 ChangeColumnName 其中,ChangeColumnName 是我们迁移的名称。这可以是任何名称。
    2. 现在,在 db/migrate/_change_column_name.rb 编辑生成的迁移文件

      class ChangeColumnName < ActiveRecord::Migration
      def change
      rename_column :table_name, :old_column, :new_column
      end
      end
      
    3. $> rake db:migrate

    您必须编辑控制器和查看文件,例如如果型号名称是 Product 那么您可能会编辑这些文件

    1. /app/views/products/_form.html.erb
    2. /app/views/products/show.html.erb
    3. /app/controllers/products_controller.erb
    4. /app/views/products/index.html.erb

    【讨论】:

    • 虽然我同意这是最佳做法,但我的问题涉及使用旧数据库,我无法在其中进行更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2015-02-01
    • 1970-01-01
    相关资源
    最近更新 更多