This is a post for outputting "Ruby on Rails 5 Quick Learning Practice Guide" in Continued from last time. This time, I will write how to make your own model validator! As an example, create a validate that does not contain hyphens in the name column of the Task model.
<!-Edit title and anchor name->
task.rb
private
def validate_not_including_hyphen
errors.add(:name, 'Do not put hyphens in!') if name&.include?('-')
This code adds an error when the name contains a hyphen instead of nil.
task.rb
validate :validate_not_including_hyphen
You can also call it with a callback (such as before_create).
- @task.errors.full_message.each do |message|
li = message
-Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field
Recommended Posts