Describe in the model file. presence: Required for true. Various other settings are possible. Please refer to the official documents for details.
profile.rb
class Profile < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :age, presence: true
validates :sex, presence: true
validates :description, presence: true
validates :qualify, presence: true
validates :impression, presence: true
end
There are various methods, but this time I used the helper ʻif @ variable name.errors.include?` to do the following. Although only the name is described, the message can be displayed by changing the name to another column name.
new.html.erb
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true, autocomplete: "name" %>
<%#The error content is displayed in red below%>
<% if @profile.errors.include?(:name) %>
<p style="color: red;"><%= @profile.errors.full_messages_for(:name).first %>
<% end %>
When displayed, it looks like the following.
This time I will use gem, but Japanese language files are available via Git.
If you are interested, please search with rails-i18n
.
Also, the column names are still in English for this task. Column names will be translated into Japanese in the next paragraph.
gem 'rails-i18n'
bundel install
Create a ja.yml
file in the config / locales / models
directory.
If the indent shifts, it will not work properly, so please refer to the image as well (number of points = indent width).
ja.yml
ja:
activerecord:
models:
profile:profile#Model name with the column you want to translate into Japanese
attributes:
profile:
name:name
age:age
sex:sex
description:Overview
qualify:Qualification
impression:enthusiasm
For reference, the contents of validation will be posted again.
profile.rb
class Profile < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :age, presence: true
validates :sex, presence: true
validates :description, presence: true
validates :qualify, presence: true
validates :impression, presence: true
end
Finally, you need to load the yml file.
Add a sentence to config / application.rb
as follows.
This will allow you to read all the yml files in your directory.
application.rb
module Association03
class Application < Rails::Application
config.load_defaults 5.1
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml').to_s] #Added one sentence
end
end
Recommended Posts