Suppose you have the following users table.
mysql> desc users;
+-----------------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(100)| NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+-----------------------------+-------------+------+-----+---------+----------------+
In this case, when creating a Rails User model, I think that name is often validated with less than 100 characters. At that time, did you hard-code 100 as shown below?
app/models/user.rb
validates :name, presence: true, length: { maximum: 100 }
Rails makes it easy to get meta information about database tables. By using this, 100 parts can be dynamically taken from the table definition as shown below.
validates :name, presence: true, length: { maximum: columns.find{|c| c.name == 'name' }.limit }
It is recommended to write like this because the validation value will be updated automatically when the table definition is changed.
Recommended Posts