Define in the model.
class User < ApplicationRecord
  validates :name, {presence: true}
  validates :email, {presence: true}
end
In the above, we have restricted empty posts for name and email.
When an error occurs, the error message will be put in an array in error.full_message.
<% if @user.errors.any? %>
  <% @user.errors.full_messages.each do |message| %>
    <%= message %>
  <% end %>  
<% end %>
If there is a @ user error, all @ user.errors.full_messages will be output.
The error message is in English by default, so let's translate it into Japanese.
Gem fileAdd the following to the Gem file and do bundle install.
 gem 'rails-i18n'
config/application.rbAdd the following to config/application.rb and restart the server.
config.i18n.default_locale = :ja
As it is, the value part of the error message is not translated into Japanese as shown below.
["Please enter name"]
Create a file called ja.yml in config/locales/models/.
Add the following to the ja.yml file.
ja:
  activerecord:
    
    attributes:
      user:
        name:name
       email:Email
Finally, add a sentence to read this yml file to config/application.rb.
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml').to_s]
done.
["Please enter your name"]
        Recommended Posts