Make your own Rails validate

Introduction

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.

table of contents

<!-Edit title and anchor name->

  1. Create your own validate method
  2. Call your own validate
  3. Display error message
  4. References

<!-Each chapter->

Create your own validate method

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.

Call your own validate

task.rb


validate :validate_not_including_hyphen

You can also call it with a callback (such as before_create).

Display an error message

- @task.errors.full_message.each do |message|
      li = message

References

-Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field

Recommended Posts

Make your own Rails validate
Make your own pomodoro
Make your own Elasticsearch plugin
Make your own persistence FW (Java)
Call your own class created under lib with Rails
Apply your own domain to Rails of VPS and make it SSL (https) (CentOS 8.2 / Nginx)
Create your own Java annotations
Make your own simple server in Java and understand HTTP
[Rails] Make a breadcrumb trail
[Rails] How to make seed
Use your own classes in the lib directory with Rails6
If you are new to Rails and want to make your own validation, stop by this finger.
Make your own keyboard QMK in Docker. Volume unique to Windows
Redirect to your own domain with rack-rewrite on Heroku x Rails
[Rails] Make pagination compatible with Ajax
Incorporate Elasticsearch into your Rails app
Create your own Solr Function Query
Use LocationAwareLogger for your own Logger
Handle your own annotations in Java
Create your own encode for String.getBytes ()
Deploy your Rails app on Heroku
Articles are getting messy, so make a link collection of your own articles