폼 유효성 검증 오류 메시지 각 입력부 하단에 표시하기 의 마지막 부분에서 에러 박스 구현부분을 삭제했었다. 이 글에서는 삭제된 에러 박스 부분을 error_explanation()
이라는 헬퍼메소드로 리팩토링하는 과정을 설명할 것이다. 삭제 전의 폼 파셜 코드는 다음과 같다.
<%= form_with(model: post, local: true) do "form %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2>글 저장 중 개의 오류가 발생했습니다.</h2>
<ul>
<% post.errors.messages.each do |message| %>
<li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title, class: 'form-control' %>
<div class="validation-error">
<%= post.errors.messages[:title].join(' ') %>
</div>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content, rows: 5, class: 'form-control' %>
<div class="validation-error">
<%= post.errors.messages[:content].join(' ') %>
</div>
</div>
<div class="actions">
<%= form.submit nil, class: 'btn btn-primary' %>
<%= link_to 'Show', @post, class: 'btn btn-outline-primary' if @post.persisted? %>
<%= link_to 'Back', posts_path, class: 'btn btn-outline-primary' %>
</div>
<% end %>
위에서 아래의 코드 부분을 발췌한 후,
<% if post.errors.any? %>
<div id="error_explanation">
<h2>글 저장 중 개의 오류가 발생했습니다.
<ul>
<% post.errors.messages.each do |message| %>
<li>
<% end %>
</ul>
</div>
<% end %>
다음과 같이
ApplicationHelper
모듈에 error_explanation()
헬퍼를 정의한다.
module ApplicationHelper
def error_explanation(model)
if model.errors.any?
content_tag(:div, id:"error_explanation") do
concat(content_tag(:h2, "글 저장 중 #{model.errors.count}개의 오류가 발생했습니다."))
concat( content_tag(:ul) do
model.errors.messages.each do |message|
concat(content_tag(:li, message.flatten[1]))
end
end
)
end
end
end
end
여기서 사용한 content_tag()
나 concat()
의 사용법에 대해서는 아래의 References를 참고하기 바란다.
이제 한줄의 명령으로 간단하게 유효성 검증 에러를 표시하거나 감출 수 있게 된다.
<%= form_with(model: post, local: true) do |form| %>
<%= error_explanation(post) %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title, class: 'form-control' %>
<div class="validation-error">
<%= post.errors.messages[:title].join(' ') %>
</div>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content, rows: 5, class: 'form-control' %>
<div class="validation-error">
<%= post.errors.messages[:content].join(' ') %>
</div>
</div>
<div class="actions">
<%= form.submit nil, class: 'btn btn-primary' %>
<%= link_to 'Show', @post, class: 'btn btn-outline-primary' if @post.persisted? %>
<%= link_to 'Back', posts_path, class: 'btn btn-outline-primary' %>
</div>
<% end %>
References :