Customize Field Error Proc - Ruby on Rails

Add this on initializer, just render the form using Turbo streams or ajax everytime model add errors.

  ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
    html_document = Nokogiri::HTML::DocumentFragment.parse(html_tag, Encoding::UTF_8.to_s)
    html_element = html_document.children[0]

    if html_element.present? # change border color of form element
      html_element.add_class("border-red-300")
      # Select inputs element and append the error message bellow the form element
      if %w[input select textarea].include?(html_element.name)
        instance.raw %(#{html_document.to_html} <div class="text-red-500">#{[*instance.error_message].to_sentence.humanize}</div>)
      else
        instance.raw html_document.to_html
      end
    else
      html_tag
    end
  end