2017-10-11 8 views
0

私は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") 
) 

を実行したときにどのように私は自分の移行が参照される列と同じ型を持つ私の列を作成するように指示しますか?

+0

私はあなたが手動で 't.stringをしなければならないと思います:address_id' とCREATE TABLEブロック ' add_foreign_key後:seach_codes、:adresses' – Kkulikovskis

答えて

1

t.references代理人ジョブをadd_referenceに委任します。これは:typeパラメータを受け入れます。このことから判断すると、あなたはだけのおもちゃのsqlite3のベースのプロジェクトでこれをテストした

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

を行うことができる必要があり、それが働きました。 pgでも「うまく動作する」必要があります。


どのように私は私の移行が参照される列と同じタイプで、私の列を作成するように指示しますか?

あなたが他の列の型を推測し、この1試合、それのタイプを持っていることを伝えるためのものならば、このことはできそうにありません。しかし、常に型を明示的に指定することができます。

関連する問題