Reference with custom name and foreign key
I'm on Rails 5 and have a User model.
I want to create a Book model, referencing the User model with the name author. I want as well to set foreign keys in the migration.
When searching an answer I have only found how to add columns in a migration, not on creating a new table. How would the below look like for create_table :books?
add_reference :books, :author, references: :users, index: true add_foreign_key :books, :users, column: :author_id
You can use author_id:integer
Then in your User model:
has_many :books, foreign_key: :author_id, class_name: "Book", dependent: :nullify
I use dependent: :nullify to avoid errors when you delete a record, but you can use dependent: :destroy if you need to destroy the books when you destroy the user.
And Book model:
belongs_to :user, foreign_key: :author_id, class_name: 'User'
You should add an index on this column.