Rails add foreign key

·

1 min read

when we want to add a foreign key in Rails

we can run this command

bin/rails g migration add_author_to_books author:references

this means one author has one or more books in the database

class AddAuthorToBooks < ActiveRecord::Migration[7.0]
  def change
    add_reference :books, :author, null: false, foreign_key: true
  end
end