私はデータベースとしてPostgreSQLを使用しているRuby On Railsアプリケーションを開発していますが、問題に直面しました。 hashid
フィールド(列)の代わりに、デフォルトの数値id
分野で使用されているマイグレーション内で参照する外部キーテーブルを指定します。
create_table "questions", primary_key: "hashid", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "questions", ["hashid"], name: "index_questions_on_hashid", unique: true, using: :btree
:ここ
は私のQuestions
テーブル(schema.rb
)です。ここで
は両方Questions
とComments
テーブルのための私の移行だ:
# Questions migration
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions, id: false do |t|
t.text :hashid, primary_key: true
t.string :title
t.text :body
t.timestamps null: false
end
add_index :questions, :hashid, unique: true
end
end
# Comments migration
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.references :question, foreign_key: :hashid
t.timestamps null: false
end
end
end
私はそれに応じてbelongs_to
とhas_many
関係を利用して自分のアプリケーションにQuestions
でComments
を関連付けるしたいのですが、デフォルトt.references :question
はid
列を使用して関連付けるしようとしていますターゲット表から。私はid
フィールド以外の使用により関連可能性がどのように
== 20160326185658 CreateComments: migrating ===================================
-- create_table(:comments)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedColumn: ERROR: column "id" referenced in foreign key constraint does not exist
: ALTER TABLE "comments" ADD CONSTRAINT "comments_question_id_fk" FOREIGN KEY ("question_id") REFERENCES "questions"(id)
:ここ
は、移行エラーメッセージのですか?私の場合、それはhashid
ですか?
なぜあなたはRailsの規約と戦いたいのですが、プライマリキーにデフォルト名 'id'を使わないのですか?あなたは何を達成しようとしますか? – spickermann
私はyoutubeのようなものを作成しようとしているので、数字のIDではなくランダムな文字列としてビデオIDを持っています。これは、デフォルトの数値idをランダムな文字列idに変更した理由です –
アプリケーションが生成するランダムな文字列を含んでいても、その列に 'id'という名前を付けることができます。他の名前を選択した場合は、移行、クラス主キー定義、ルーティング、ファインダなど多くの異なる問題を修正する必要があります。 – spickermann