Skip to content

Instantly share code, notes, and snippets.

@ahmad19
Last active November 1, 2024 17:06
Show Gist options
  • Save ahmad19/9092275c6c87a8ac6699df9362b06023 to your computer and use it in GitHub Desktop.
Save ahmad19/9092275c6c87a8ac6699df9362b06023 to your computer and use it in GitHub Desktop.
Render inline errors in Rails forms after submit
<%= 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 %>
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
@ahmad19
Copy link
Author

ahmad19 commented Jun 4, 2021

This is how it will be displayed after the form submit

form_errors

@ahmad19
Copy link
Author

ahmad19 commented Jun 6, 2021

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

@vasilevskykv
Copy link

This code doesn't work. I got an error:
"cannot load such file -- I:/RB/proj/AskIt/app/controllers/InlineErrorRenderer.rb"

@ahmad19
Copy link
Author

ahmad19 commented May 10, 2023

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