rails error message displays key and I only want value
full_messages
method prepends attribute name
to the validation error message
.
Following is the method implementation in rails
## Following code is extracted from Rails source code
def full_messages
map { |attribute, message| full_message(attribute, message) }
end
def full_message(attribute, message)
return message if attribute == :base
attr_name = attribute.to_s.tr('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
I18n.t(:"errors.format", {
default: "%{attribute} %{message}",
attribute: attr_name,
message: message
})
end
If you see the full_messages
method it in turn calls full_messages
wherein attribute gets prepended to the error message.
So, if you add attribute name
in the validation error message
it is definitely going to be duplicated which is what is happening in your case.
In nutshell, you don't need to specify attribute name in validation message, as rails is already taking care of it.
EDIT
Nothing is impossible. If you want you could customize it as below
<% if @profile.errors.any? %>
<ul>
<% @profile.errors.messages.each do |attr, msg| %>
<% msg.each do |val| %>
<li><%= val %></li>
<% end %>
<% end %>
</ul>
<% end %>
Rails validation error messages: Displaying only one error message per field
Bert over at RailsForum wrote about this a little while back. He wrote the code below and I added some minor tweaks for it to run on Rails-3.0.0-beta2.
Add this to a file called app/helpers/errors_helper.rb
and simply add helper "errors"
to your controller.
module ErrorsHelper
# see: lib/action_view/helpers/active_model_helper.rb
def error_messages_for(*params)
options = params.extract_options!.symbolize_keys
objects = Array.wrap(options.delete(:object) || params).map do |object|
object = instance_variable_get("@#{object}") unless object.respond_to?(:to_model)
object = convert_to_model(object)
if object.class.respond_to?(:model_name)
options[:object_name] ||= object.class.model_name.human.downcase
end
object
end
objects.compact!
count = objects.inject(0) {|sum, object| sum + object.errors.count }
unless count.zero?
html = {}
[:id, :class].each do |key|
if options.include?(key)
value = options[key]
html[key] = value unless value.blank?
else
html[key] = 'errorExplanation'
end
end
options[:object_name] ||= params.first
I18n.with_options :locale => options[:locale], :scope => [:errors, :template] do |locale|
header_message = if options.include?(:header_message)
options[:header_message]
else
locale.t :header, :count => count, :model => options[:object_name].to_s.gsub('_', ' ')
end
message = options.include?(:message) ? options[:message] : locale.t(:body)
error_messages = objects.sum do |object|
object.errors.on(:name)
full_flat_messages(object).map do |msg|
content_tag(:li, ERB::Util.html_escape(msg))
end
end.join.html_safe
contents = ''
contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank?
contents << content_tag(:p, message) unless message.blank?
contents << content_tag(:ul, error_messages)
content_tag(:div, contents.html_safe, html)
end
else
''
end
end
####################
#
# added to make the errors display in a single line per field
#
####################
def full_flat_messages(object)
full_messages = []
object.errors.each_key do |attr|
msg_part=msg=''
object.errors[attr].each do |message|
next unless message
if attr == "base"
full_messages << message
else
msg=object.class.human_attribute_name(attr)
msg_part+= I18n.t('activerecord.errors.format.separator', :default => ' ') + (msg_part=="" ? '': ' & ' ) + message
end
end
full_messages << "#{msg} #{msg_part}" if msg!=""
end
full_messages
end
end
How do I display Ruby on Rails form validation error messages one at a time?
After experimenting for a few hours I figured it out.
<% if @user.errors.full_messages.any? %>
<% @user.errors.full_messages.each do |error_message| %>
<%= error_message if @user.errors.full_messages.first == error_message %> <br />
<% end %>
<% end %>
Even better:
<%= @user.errors.full_messages.first if @user.errors.any? %>
Attribute name showing on Devise Error
You are calling full_messages
method in the overridden devise_error_messages!
of your devise helper. full_messages
method prepends attribute name
to the validation error message
.
Replace
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
with
messages = resource.errors.messages.map { |attr,msg| content_tag(:li, msg.join(', ')) }.join
See my answer for this SO question to get a better idea.
Rails 3 - get full error message for one field
Well, I know this question was explicitly posted for Rails 3.x, one and a half years ago, but now Rails 4.x seems to have the very method you were wishing, full_messages_for
.
user.errors.full_messages_for(:user_login) #=> return an array
# if you want the first message of all the errors a specific attribute gets,
user.errors.full_messages_for(:user_login).first
# or
user.errors.full_messages_for(:user_login)[0]
It's less verbose than the previously used user.errors.full_message(:user_login, user.errors[:user_login].first)
.
how to display devise error messages when i'm putting the login in and sign up forms in same page
I found the solution to this problem on StackOverFlow some time ago. Here's what worked for me
# In application.html.erb
<% flash.each do |name, msg| %>
# New code (allow for flash elements to be arrays)
<% if msg.class == Array %>
<% msg.each do |message| %>
<%= content_tag :div, message, :id => "flash_#{name}" %>
<% end %>
<% else %>
# old code
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %> #don't forget the extra end
<% end %>
and
# Wherever you want Devise's error messages to be handled like
# your other error messages
# (in my case, registrations_controller.rb, a custom controller)
flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
See original post here
...and think about accepting answer, 50% is a bit low! ;)
===== EDIT =====
If you need to redirect to another page when errors occurs, you'll have to override controllers (check Devise Wiki or search stackoverflow for howto) but it should look like something like that
# CUSTOM DEVISE CONTROLLER
class RegistrationsController < Devise::RegistrationsController
# POST /resource
def create
build_resource
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => redirect_location(resource_name, resource)
else
set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords(resource)
# Solution for displaying Devise errors on the homepage found on:
# https://stackoverflow.com/questions/4101641/rails-devise-handling-devise-error-messages
flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
redirect_to root_path # HERE IS THE PATH YOU WANT TO CHANGE
end
end
end
Display the error message after the label title
I found the answer and I am posting here so that it might help somebody.
In the simple for configuartion file just put the error tag before input like this :
b.use :error, wrap_with: { tag: :span, class: :error }
b.use :label_input
And add this css on error class:
float:right
Thanks
Sabbu
Fully custom validation error message with Rails
Now, the accepted way to set the humanized names and custom error messages is to use locales.
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
errors:
models:
user:
attributes:
email:
blank: "is required"
Now the humanized name and the presence validation message for the "email" attribute have been changed.
Validation messages can be set for a specific model+attribute, model, attribute, or globally.
Related Topics
Upsert Multiple Records with Mongodb
How to Search for Useful Ruby Gems
Detect Similar Sounding Words in Ruby
Shortening Socket Timeout Using Timeout::Timeout(N) Does Not Seem to Work for Me
Why Does the Rand() Return Always the Same Number
What Is the Advantage of Creating an Enumerable Object Using To_Enum in Ruby
Garbage Collector in Ruby 2.2 Provokes Unexpected Cow
Ruby on Rails. Bundler. Cucumber. Rake Aborted! Command Failed with Status (1)
How to Remove a Row from a CSV with Ruby
Post Redirect Get Pattern in Rails
Ruby on Rails: Radio Buttons for Collection Select
Ruby -- Capitalize First Letter of Every Sentence in a Paragraph
Ruby Regex to Capture Everything Between Two Strings (Inclusive)
Ruby on Rails How to Deal with Nan
Flash Message with HTML_Safe from the Controller in Rails 4 (Safe Version)