Database Constraints

It is very important to make sure your data in the right format.

You should always add a t.bigint user_id, null: false if you always want a post to have author. A boolean field always defaults to false: default: false. A unique index to make sure no other user could have the same profile: add_index :profiles, :user_id, unique: true. A foreign key to achieve referential integrity.

Rails or framework’s validation does not enforce these to happen. You could still insert whatever you want to the database. Validation is a way at code level to tell the developers during development what kind of data they can put into the database. If you dont want any of situation to happen on production, enforce it at database level.

And no, has_one does not gurantee there is only one record. We have to add a database constraint by ourselves. And no, has_many :comments, dependent: :destroy did not help when you delete_all user’s comments. We should add a add_foreign_key :users, :comments, on_delete: :cascade.