Search code examples
foreign-keysrails-activerecordrails-migrationsrails-postgresqlruby-on-rails-5.1

How do I create a foreign key in rails 5 if I've already created the models for the tables I want to associate?


All of the references I've found either show me how to do it upon table creation, or are for a much earlier version of rails. Ideally, I'd like like the foreign_key to be named 'author_id' in the questions table to distinguish it from other users who may be leaving comments or answers later.

class Question < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :questions
end

Solution

  • You can create a new empty migration file in your terminal via rails generate migration RenameUserFkOnQuestion. Open it up and build your migration. This is a handy guide if you're not sure on the name of something.

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

    Run the migration and head over to your models. You'll need to update your relationships like so:

    class Question
      belongs_to :author, class_name: 'User'
    end
    
    class User
      has_many :questions, inverse_of: :author
    end
    

    Then you should be good to go.