【问题标题】:How do I tell my migration what column type to use?如何告诉我的迁移使用哪种列类型?
【发布时间】:2017-10-11 20:35:27
【问题描述】:

我正在使用 Rails 5 和 PostGres 9.5。我已经创建了这个迁移

class CreateSearchCodeTable < ActiveRecord::Migration[5.0]
  def change
    create_table :search_codes do |t|
      t.string :code
      t.references :address, index: true, foreign_key: true, on_delete: :cascade
      t.index ["code"], name: "index_search_codes_on_code", unique: true, using: :btree
    end
  end
end

但地址表的 ID 列不是整数。也许出于这个原因,我在运行迁移时收到以下错误

== 20171011202623 CreateSearchCodeTable: migrating ============================
-- create_table(:search_codes)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_6bd9792e3b" cannot be implemented
DETAIL:  Key columns "address_id" and "id" are of incompatible types: integer and character varying.
: CREATE TABLE "search_codes" ("id" serial primary key, "code" character varying, "address_id" integer, CONSTRAINT "fk_rails_6bd9792e3b"
FOREIGN KEY ("address_id")
  REFERENCES "addresses" ("id")
)

如何指示我的迁移创建与引用列具有相同类型的列?

【问题讨论】:

  • 我猜你必须手动执行此操作t.string :address_id 并在创建表块之后add_foreign_key :seach_codes, :adresses

标签: postgresql foreign-keys migration ruby-on-rails-5


【解决方案1】:

t.references 将工作委托给add_reference,并且这个接受:type 参数。由此看来,你应该能够做到

t.references :address, type: :string, index: true, foreign_key: true, on_delete: :cascade
                       ^^^^^^^^^^^^^

刚刚在一个基于 sqlite3 的玩具项目上进行了测试,它确实有效。也应该在 pg 上“正常工作”。


如何指示我的迁移创建与引用列具有相同类型的列?

如果您打算告诉它推断另一列的类型并让这一列的类型与之匹配,那么这可能是不可能的。但您始终可以明确指定类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2019-03-27
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多