I will summarize the validation used in the current application creation.
with_options
Taking frequently used validation as an example
model
validates :user, presence: true
validates :item, presence: true
validates :price, presence: true
validates :email, presence: true
It's just the same thing, it's getting longer and more readable ...
In such a case, you can set validation collectively with with_options
.
model
with_options presence: true do
validates :user
validates :item
validates :price
validates :email
end
model
with_options presence: true do
validates :user, length: { minimum: 6 }
validates :item
validates :price, format: { with: /\A[0-9]+\z/ }
validates :email
end
Validation can be added individually in do ~ end. By the way, the length option can limit the number of characters. The format option specifies a regular expression.
model
with_options presence: true do
validates :user
validates :item
with_options uniqueness: true do
validates :price
validates :email
end
end
You can nest with_options inside with_options.
In the above example,
presence: true
is set to: user,: item,: price,: email,
In addition, ʻuniqueness: true` is set to: price,: email.
By the way, the uniqueness option prevents you from saving the same value. (Uniqueness)
Writing together with with_options is similar to the feeling of wrapping up in common terms per factorization learning that appeared in junior high school mathematics.
Recommended Posts