I learned that there is a way to specify constraints when saving data for migration files and model files, so I tried to summarize typical validations again. (I studied a long time ago, but I will summarize it in qiita again.)
macOS Catalina 10.15.7 VS Code 1.50.0 Ruby 2.6.5 Rails 6.0.0
→ Restriction that cannot be saved when the data is empty
[How to write in the migration file] null: false
20200919092740_create_item.rb
t.string :address, null: false
[How to write in the model file] presence: true
item.rb
validates :address, presence: true
→ Restriction that the same data cannot be saved more than once [How to write in the migration file] unique: true
20200919092740_create_item.rb
t.string :address, unique: true
[How to write in the model file] uniqueness: true
item.rb
validates :address, uniqueness: true
→ Restriction that data cannot be saved when it is empty and the same data cannot be saved more than once. (NOT NULL constraint and unique constraint) (Restrictions set automatically for id column)
[How to write in the migration file] primary_key: true
20200919092740_create_item.rb
t.string :address, primary_key: true
→ Restriction that data cannot be saved unless the data that becomes the foreign key always exists
[How to write in the migration file] foreign_key: true
20200919092740_create_item.rb
t.string :address, foreign_key: true
Recommended Posts