ruby-on-rails - Heroku : undefined table/relation doesn't exist for foreign key 上的第一次数据库迁移

标签 ruby-on-rails postgresql activerecord

错误信息:PG::UndefinedTable: ERROR: relation "resolvers"does not exist

这是吐出错误的迁移:

class AddResolverRefToBugs < ActiveRecord::Migration[5.0]
  def change
    add_reference :bugs, :resolver, foreign_key: true
  end
end

现在,我知道没有 Resolver 表,因为实际的表是 User 表; resolver_id 是我的 foreign_key 列。因此,对于我的其中一个引用用户模型的模型,我只有一个 resolver_id 字段,而且我的应用程序在开发环境中没有任何问题。

class Bug < ApplicationRecord
  # Associations
  belongs_to :user
  belongs_to :resolver, class_name: 'User', optional: true

我是否应该在某处指定一些内容,以便 PG 知道 :resolver(resolver_id 列)实际上是 Users 表?

我的错误消息包含以下行:: ALTER TABLE "bugs"ADD CONSTRAINT "fk_rails_2d3f1765bb"FOREIGN KEY ("resolver_id") REFERENCES "resolvers"("id")

所以它看起来确实引用了错误的东西。

在一个相关的StackOverflow question , 我注意到他/她有“嵌套”引用...

create_table :english_grades do |t|
  t.references :teacher, references: :users
  t.references :student, references: :users

...指定用户的位置。我不确定这在这里是否相关。

大概我的模式我的迁移可能看起来像:

t.references :resolver, references: users

docs for add_references别提这件事。

那个人还在迁移中指定了外键,我确实看到了从外键字段到实际表的链接。大概我需要这样的东西:

add_foreign_key :bugs, :users, column: :resolver_id

但根据我在网上阅读的内容,没有必要使用add_foreign_key

如有任何解释,我将不胜感激。

注意:有些人建议先运行 db:reset,但这对我不起作用,因为我得到了 error this person is getting。 .

最佳答案

我仍然不确定为什么 Postgres 会在此处抛出错误而 Sqlite 不会。但是,将解析器列正确引用到用户表的一种方法是使用 foreign_key: {to_table::users}:

add_reference :bugs, :resolver, foreign_key: {to_table: :users}

在摆脱原来的 add_reference 迁移之后。 PG 在用这条线进行迁移时没有提示。

( rails 5)

关于ruby-on-rails - Heroku : undefined table/relation doesn't exist for foreign key 上的第一次数据库迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838091/

相关文章:

django - 错误 : Permission denied when trying to create database django

postgresql - 无法在 WSL Ubuntu 上启动 postgresql

ruby-on-rails - 在初始化时建立关联以满足委托(delegate)的需求

ruby-on-rails - 使用一个查询在 Rails 中使用 ActiveRecord 同时更新多条记录?

ruby-on-rails - 我如何 stub results.map(& :blank_image) in Rspec?

postgresql - 克洛贾尔/后gresql : How do I access the enum values from the Jdbc4Array results?

ruby-on-rails - 在 OR 而不是 AND 上合并 2 个关系

ruby-on-rails - 将Sass-rails gem升级到5.0会提供弃用警告

ruby-on-rails - 带有黑名单值的 Ruby 正则表达式

ruby-on-rails - 未定义的方法 `spec' #<ActiveRecord::ConnectionAdapters::NullPool:0x00007fd44f8ab300> - Rails 6 schema:load