I'm a beginner with no programming experience, but I finished Progate's Ruby on Rails course a while back.
When I reviewed it while doing the Rails tutorial, it didn't come out very well when I was doing Progate, but now that I can understand a little more, I would like to summarize what I noticed. This article is part 2. Click here for Part 1 https://qiita.com/HiMinmeg/items/1e29bf9252096d463f6b
I hope it will be useful for those who are progate but have not come to the point and think that they do not understand here.
After validation, if an error occurs in the post (such as entering more than the limit number of characters ...), an error message will be displayed.
At this time, I didn't understand the reason for using the each statement. It was natural when I thought about it, but I was happy when I understood it, so I would like to record it.
The each statement in the error message is used as in the example.
<% @post.errors.full_messages.each do |message| %>
<%= message %>
<% end %>
ʻErrors.full_messages` gets the error contents as an array.
Reference article https://qiita.com/ryuuuuuuuuuu/items/1a1e53d062bff774d88a [Rails Guide 7. Corresponding to validation error](https://railsguides.jp/active_record_validations.html#%E3%83%90%E3%83%AA%E3%83%87%E3%83%BC%E3 % 82% B7% E3% 83% A7% E3% 83% B3% E3% 82% A8% E3% 83% A9% E3% 83% BC% E3% 81% AB% E5% AF% BE% E5% BF % 9C% E3% 81% 99% E3% 82% 8B) [Rails Guide 8. Display validation errors in view](https://railsguides.jp/active_record_validations.html#%E3%83%90%E3%83%AA%E3%83%87%E3%83%BC % E3% 82% B7% E3% 83% A7% E3% 83% B3% E3% 82% A8% E3% 83% A9% E3% 83% BC% E3% 82% 92% E3% 83% 93% E3 % 83% A5% E3% 83% BC% E3% 81% A7% E8% A1% A8% E7% A4% BA% E3% 81% 99% E3% 82% 8B)
The point here is that if multiple validations are applied, there will be multiple arrays to be acquired with the error content. Therefore, it is necessary to extract the contents of the array one by one with the each statement. There is a possibility that multiple errors will occur at the same time, so I wasn't thinking about it at all, so I was wondering why it was an each statement.
-ʻErrors.full_messages` gets the error contents as an array. -If multiple refinements are applied, there are multiple arrays to be acquired depending on the error content, so it is necessary to extract the contents of the array one by one with each statement.
Thank you for reading this far. If you make a mistake, please let us know in the comments. I hope it helps.
Recommended Posts