Created
December 7, 2021 21:28
-
-
Save pinzonjulian/7f291eba0a7229dbf1eac845553b049f to your computer and use it in GitHub Desktop.
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 ExampleFormBuilder < ActionView::Helpers::FormBuilder | |
def error(method, error_text = nil, options = {}) | |
return if errors_blank?(method) && error_text.blank? | |
text = if error_text | |
error_text | |
elsif object.errors.custom_messages_for(method) | |
object.errors.custom_messages_for(method).to_sentence | |
else | |
object.errors.full_messages_for(method).to_sentence | |
end | |
@template.content_tag(:p, text, options) | |
end | |
private | |
def errors_present?(method) | |
object.errors.where(method).present? | |
end | |
def errors_blank?(method) | |
!errors_present?(method) | |
end | |
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
# Version 1: Allow a form builder method to decide which error to use | |
<%= form_with(model: @user, builder: ExampleFormBuilder) do |form| %> | |
<%= form.text_field :name %> | |
<%= form.errors :name %> | |
<% end %> | |
# Version 2: Pass the error explicitly from the template | |
<%= form_with(model: @user, builder: ExampleFormBuilder) do |form| %> | |
<%= form.text_field :name %> | |
<%= form.errors :name, form.object.custom_errors_for(:name).to_sentence || form.object.custom_errors_for(:name).to_sentence %> | |
<% 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 User < ApplicationRecord | |
validates :name, presence: true | |
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 UsersController < ApplicationController | |
def new | |
@user = User.new | |
end | |
def create | |
@user = User.new(user_params) | |
if @user.save | |
redirect_to @user | |
else | |
render :new, status: :unprocessable_entity | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment