0

私が見つけたすべての参考文献は、テーブルの作成時にそれを行う方法を示すか、はるかに前のバージョンのレール用です。理想的には、後でコメントや回答を残している可能性のある他のユーザーと区別するために、foreign_keyの名前を「author_id」にすることが理想的です。関連付けるテーブルのモデルをすでに作成している場合、どのようにして外部キーをレール5に作成しますか?

class Question < ApplicationRecord 
    belongs_to :user 
end 

class User < ApplicationRecord 
    has_many :questions 
end 

答えて

0

rails generate migration RenameUserFkOnQuestion経由で新しい空のマイグレーションファイルを端末に作成できます。それを開き、移行を構築します。 This is a handy guide何かの名前がわからない場合は、

def change 
    change_table :questions do |t| 
    t.rename :user_id, :author_id 
    end 
end 

移行を実行して、モデルに向かいます。あなたは次のようにあなたの関係を更新する必要があります:

class Question 
    belongs_to :author, class_name: 'User' 
end 

class User 
    has_many :questions, inverse_of: :author 
end 

あなたは良いことがあります。

関連する問題