[Rails] Let's dynamically get the threshold of model validation "length check" from table information

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

[Rails] Let's dynamically get the threshold of model validation "length check" from table information
How to get the longest information from Twitter as of 12/12/2016
Check the migration status of rails
[Rails] Get a unique record from the table joined by the join method of Active Record (Rails Tutorial Chapter 14)
[Java] Get the length of the surrogate pair string
Let's check the feel of Spring Boot + Swagger 2.0
[Swift] Use Swity JSON to easily get information from JSON data of the fortune-telling API
[Rails / Uniqueness constraint] How to check model validation on the console / Uniqueness constraint for multiple columns
From the introduction of devise to the creation of the users table
[Rails] How to change the column name of the table
[Rails] Cancel / change the default password validation of devise
[Rails] How to get the contents of strong parameters
I can't get out of the Rails dbconsole screen
I want to fetch another association of the parent model from the intermediate table with has_many
[Ruby On Rails] How to search and save the data of the parent table from the child table