2016-03-26 4 views
0

私はデータベースとして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)です。ここで

は両方QuestionsCommentsテーブルのための私の移行だ:

# 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_tohas_many関係を利用して自分のアプリケーションにQuestionsCommentsを関連付けるしたいのですが、デフォルトt.references :questionid列を使用して関連付けるしようとしていますターゲット表から。私は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ですか?

+0

なぜあなたはRailsの規約と戦いたいのですが、プライマリキーにデフォルト名 'id'を使わないのですか?あなたは何を達成しようとしますか? – spickermann

+0

私はyoutubeのようなものを作成しようとしているので、数字のIDではなくランダムな文字列としてビデオIDを持っています。これは、デフォルトの数値idをランダムな文字列idに変更した理由です –

+0

アプリケーションが生成するランダムな文字列を含んでいても、その列に 'id'という名前を付けることができます。他の名前を選択した場合は、移行、クラス主キー定義、ルーティング、ファインダなど多くの異なる問題を修正する必要があります。 – spickermann

答えて

1

ランダム生成文字列が列に含まれている場合でも、プライマリキー列の名前はまだidです。 idが作成されていることを確認し、お使いのモデルでは

create_table :questions, id: false do |t| 
    # primary key should not be nil, limit to improve index speed 
    t.string :id, limit: 36, primary: true, null: false 
    # other columns ... 
end 

class Question < ActiveRecord::Base 
    before_validation :generate_id 

private 
    def generate_id 
    SecureRandom:uuid 
    end 
end 

をすでにしているとき

は、このような移行を使用し、データベース内の文字列 id列を作成するにはRails 5の場合は、 before_validationコールバックと generate_idメソッドの代わりに has_secure_token :idを使用するだけです。

関連する問題