Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 884
Fellow Stranger Avatar asked Mar 25 '16 20:03

Fellow Stranger


1 Answers

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.

like image 122
coding addicted Avatar answered Sep 19 '22 20:09

coding addicted