Last active
November 1, 2024 17:06
-
-
Save ahmad19/9092275c6c87a8ac6699df9362b06023 to your computer and use it in GitHub Desktop.
Render inline errors in Rails forms after submit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= form_with(model: post) do |form| %> | |
<% error_handler = ::InlineErrorHandler.new(post, self) %> | |
<div> | |
<%= form.label :title, style: "display: block" %> | |
<%= form.text_field :title %> | |
<%= error_handler.error_message_for(:title) %> | |
</div> | |
<div> | |
<%= form.label :body, style: "display: block" %> | |
<%= form.text_area :body %> | |
<%= error_handler.error_message_for(:body) %> | |
</div> | |
<div> | |
<%= form.submit %> | |
</div> | |
<% end %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InlineErrorHandler | |
def initialize(model, view_context) | |
@model = model | |
@view_context = view_context | |
end | |
def error_message_for(attribute) | |
if errors[attribute].present? | |
@view_context.content_tag(:span, errors[attribute].join(", "), class: "error") | |
end | |
end | |
private | |
attr_reader :model, :view_context | |
def errors | |
@errors ||= model.errors | |
end | |
end |
With hotwire added, it stays on the same page customers/new
and renders the errored state of the form.
Screen.Recording.2021-06-06.at.11.20.52.AM.mov
This code doesn't work. I got an error:
"cannot load such file -- I:/RB/proj/AskIt/app/controllers/InlineErrorRenderer.rb"
This code doesn't work. I got an error: "cannot load such file -- I:/RB/proj/AskIt/app/controllers/InlineErrorRenderer.rb"
@vasilevskykv class InlineErrorRenderer
is meant to be a service class and not a controller. Add that file in a new folder inside app called as service and then create a file with the name inline_error_renderer.rb
and then paste that code. It should work then.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how it will be displayed after the form submit