Link to user name and foreign key

I am on Rails 5 and have a User model.

I want to create a Book model, referencing a User model called author . I also want to set foreign keys during the migration process.

When searching for an answer, I discovered how to add columns to a hyphen, rather than create a new table. What looks below for create_table :books ?

 add_reference :books, :author, references: :users, index: true add_foreign_key :books, :users, column: :author_id 
+5
source share
2 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 dependency :: nullify to avoid errors when deleting a record, but you can use depend :: destroy if you need to destroy books when you destroy a user.

And the book model:

 belongs_to :user, foreign_key: :author_id, class_name: 'User' 

You should add an index to this column.

+4
source

In the rail generator instructions:

 rails g model Book user:references 
-1
source

Source: https://habr.com/ru/post/1245792/


All Articles