【问题标题】:create column name suffix with _id without parent table in rails4在rails4中创建没有父表的_id列名后缀
【发布时间】:2015-02-12 07:27:30
【问题描述】:

作为将我的 rails 应用程序升级到 rails 4 的一部分,我执行了命令 rake db:migrate,因为我使用了带有 id (supply_ref_id) 的列名,所以它被归档了。我知道 rails 会引用父表,因为我在后缀中使用了_id。但是,它在 Rails

任何使它起作用的建议。谢谢。

PG::UndefinedTable: ERROR:  relation "supply_refs" does not exist
...
...
CONSTRAINT fk_users_supply_ref_id FOREIGN KEY ("supply_ref_id")
REFERENCES "supply_refs" ("id")) /usr/local/rvm/gems/ruby-2.1.2@demo/gems/activerecord-4.1.9/lib/active_record/connection_adapters/postgresql/
database_statements.rb:128:in `async_exec'

【问题讨论】:

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


    【解决方案1】:

    Rails 不关心“外键”列名的“_id”后缀,除非您定义了关联,例如 belongs_to: supply_ref。甚至这种关联也可以配置为使用“_id”约定所暗示的“外键”列的另一个名称。

    我已经快速实现了您的示例并且没有任何错误:

    class CreateFoos < ActiveRecord::Migration
      def change
        create_table :foos do |t|
          t.string :name
          t.string :type
          t.integer :supply_ref_id
    
          t.timestamps
        end
      end
    end
    
    
    Foo.create(name: 'foo', supply_ref_id: 4711)
     => #<Foo id: 1, name: "foo", type: nil, supply_ref_id: 4711, created_at: "2015-02-12 09:11:01", updated_at: "2015-02-12 09:11:01">
    

    错误实际上是说,在您的 postgres 数据库中定义了一些 FOREIGN KEY CONSTRAINT(或 rails 尝试定义它)。它引用了不存在的supply_refs 表。

    Rails 实际上并没有默认定义外键约束。见3.6 Foreign Keys。所以它们要么是在迁移中定义的,要么是在其他 3d 派对 gem 中定义的,比如foreigner。

    如果您没有 supply_refs 表,则应删除此外键定义。

    【讨论】:

    • 我有同样的问题,但我不使用“外国人”gem,我不知道它是哪个gem。有没有办法解决这个问题?因为 rake db:migrate 在尝试创建时一直失败外键约束。
    • Grep 'add_foreign_key' 的迁移代码这是现在的默认迁移方法,您可以在文档中看到链接到答案
    【解决方案2】:

    确保您的依赖关系树中没有 schema_plus。

    如果是这样,这可以解决您的问题。

    class CreateFoos < ActiveRecord::Migration
      def change
        create_table :foos do |t|
          t.string :name
          t.string :type
          t.integer :supply_ref_id, foreign_key: false
    
          t.timestamps
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多