Hide/remove model name in association error message - ruby-on-rails

For the life of me, I cannot find how to remove "model name" before the error message. Typically this would be ok but hear me out.
I have a model called 'foo'. I'd need to rename it at some point but for now it's a hassle. For now, I need to change the error message: "Foo How often you get paid is missing".
# finance.rb
belongs_to :foo # this will be renamed in the future
[..]
I thought I needed to edit the en.yml only:
en:
activerecord:
errors:
models:
finance:
attributes:
foo:
required: "How often you get paid is missing"
This works but I don't need to show the model's name with the message. Ok I could do some string replace but that's ugly. Is it possible to only show the message in the en.yml?
EDIT:
Error are displayed as:
<% if #finance.errors.any? %>
<ul>
<% #finance.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>

Seems to be an easy solution found here. So in my case:
en:
errors:
format: "%{message}"
activerecord:
errors:
models:
finance:
attributes:
repayment_type:
required: "How often you get paid is missing"
This could be a duplicate post so you could mark as duplicate 🙂

Related

How to capitalize all Rails Activerecord form validation messages

I am trying to perform a simple customization on all of the validation error messages on a form in my rails app. Simply, I want to go from: can't be blank and is invalid to Can't be blank, Is invalid, etc. Is there a way to do this in my translations that won't require customizing every single individual error message?
If you have a class or some way of creating a css selector you can use:
.error-msg:first-letter{
text-transform: capitalize
}
Another option is you could change your config/locales/en.yml file like so:
en:
errors:
messages:
blank: "Can't be blank"
invalid: "Is invalid"
...
You could try changing it in your view using the capitalize method.
In your view:
<% m.errors.each do |attr, msg| %>
<%= msg.capitalize %>
<% end %>

Remove attribute name from locales error message

I've got a set of locales, as listed below. When an error message is triggered, it will pull in the name of the attribute and prepends it before the error message.
The error result for the points value being blank on submit is, "value points value can't be blank".
How do I remove the {%attribute} name in the error message?
en:
activerecord:
attributes:
referral:
email: The email address you entered
errors:
models:
answer:
attributes:
value:
blank: points value can't be blank
I've also tried to add the message in the model, but to no avail (it still prepends the attribute name).
validates_presence_of :value, :message => "points value can't be blank"
Thanks in advance!
I would do this by localizing the attribute name, rather than prevent it from being added to the message:
en:
activerecord:
attributes:
answer:
value: "points"
You could try accessing each message value from the errors in the object you're trying to create, and within each message, to access it's first value (as it's an array), something like:
<% answer.errors.messages.values.each do |message| %>
<li><%= message.first %></li>
<% end %>

Where do I set template for rails error messages?

I want rails to show error message
Field <field name> can't be blank
but using standard means I get
<field name> Field <field name> can't be blank
Here's a minimal example reproducing the problem:
rails new test
cd test
rails g scaffold user name
rake db:migrate
Add validation to app/models/user.rb:
class User < ActiveRecord::Base
validates :name, presence: true
end
Edit config/locale/en.yml to be:
en:
activerecord:
attributes:
user:
name: "Name"
errors:
models:
user:
attributes:
name:
blank: "Field %{attribute} can't be blank"
After this start the server
rails s
point browser to http://localhost:3000/users/new and press "Create User" button. You'll get:
Apparently, there's another template somewhere, which says something like
%{attribute} %{message}
but I can't find it in rails code.
This is because in a standard view generated by scaffold (views/users/_form.html.erb) you have:
<% user.errors.full_messages.each do |message| %>
This is what returns
Name Field Name can't be blank
Instead, you can modify the _form view and use user.errors.messages, where you get a hash with errors assigned to keys representing fields:
#user.errors.messages
{:name=>["Field Name can't be blank"]}
To get what you expect you could write for example:
<% #user.errors.messages.values.flatten.each do |message| %>
<li><%= message %></li>
<% end %>

Model name appearing in my validation error in Rails

I'm still struggling to get my validation error message to display without the name of the model appearing in it, I have a nested model called AnimalImage and am performing a validation on whether a file has been submitted.
def limit_num_of_images
if image.size < 1
errors.add(:base, "Please add an image")
ap(errors.inspect)
end
end
The error I get in this instance is:
Animal images base Please add an image
All I want to show is:
Please add an image
Looking in the console the output of errors.inspect is
"#<ActiveModel::Errors:0x007fa0192d1890 #base=#<AnimalImage id: nil, animal_id: nil, image: nil, created_at: nil, updated_at: nil>, #messages={:base=>[\"Please add an image\"]}>"
So the messages are in a hash? if that's the case I need to find a way of not displaying the key?
Finally in my view I am outputting the error messages like so
<% #animal.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
So as a quick fix I have created a helper that just strips out the first part of the text, but this feels too hacky and I would like to know how to do it properly with Rails:
def error_edit(message)
msg = message
msg.gsub('Animal images base', ' ')
end
// View
<% #animal.errors.full_messages.each do |msg| %>
<li><%= error_edit(msg) %></li>
<% end %>
I had the same problem in my controller. I know its not a better solution but I am sure it will give you an idea.
Please don't use
errors.add(:base, "Please add an image")
User this
errors.add(:attribute, "Please add an image")
<% #animal.errors.each do |key,value| %>
<li><%= "#{key.to_s.titleize} #{value}".html_safe %></li>
<% end %>
I think this will work for you
class Animal < ActiveRecord::Base
validate do |animal|
animal.errors[:base] << "Please add an image" if animal.image.size < 1
end
end
I will also suggest you looking at this link http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add
Adds message to the error messages on attribute.
what you are doing is adding the message on an attribute called base, which is obviously not what you would like to have
update: add_to_base method was removed from rails 3. You should use errors[:base] << "error" instead.

Error messages always include attribute name

I have the following validation error messages coming up when I try to submit a blank form:
Start time time Looks like you forgot the appointment start time.
Start time time Sorry, we can't understand "" as a time.
Start time ymd Please choose a date for the appointment.
Start time ymd Sorry, we can't understand "" as a date.
Stylist services Please choose at least one service.
These messages are for the following attributes:
start_time_time
start_time_time
start_time_ymd
start_time_ymd
stylist_services
I included the attribute names so you could plainly see which part of the error message is the attribute name.
How do I remove the attribute names from the error messages?
In rails 3.2.6, you can supress the inclusion of the attribute name by setting errors.format in a locale file (e.g., config/locales/en.yml):
en:
errors:
format: "%{message}"
Otherwise, the default format is "%{attribute} %{message}".
It's common to loop over object.full_messages to output each full message:
<% if object.errors.any? %>
<h2>Errors</h2>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<h2>Errors</h2>
<ul>
<li>Start time time Looks like you forgot the appointment start time.</li>
<li>Start time time Sorry, we can't understand "" as a time.</li>
<li>Start time ymd Please choose a date for the appointment.</li>
<li>Start time ymd Sorry, we can't understand "" as a date.</li>
<li>Stylist services Please choose at least one service.</li>
</ul>
But a "full" message consists of the localized field name followed by the message (as you've seen; this is because the messages are usually things like "can't be blank"). If you just want the actual error message minus the field name, use the built-in each iterator instead:
<% if object.errors.any? %>
<h2>Errors</h2>
<ul>
<% object.errors.each do |field, msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<h2>Errors</h2>
<ul>
<li>Looks like you forgot the appointment start time.</li>
<li>Sorry, we can't understand "" as a time.</li>
<li>Please choose a date for the appointment.</li>
<li>Sorry, we can't understand "" as a date.</li>
<li>Please choose at least one service.</li>
</ul>
You could use the i18n route to change the display name of the attribute.
config/locales/en.yml:
en:
activerecord:
attributes:
somemodel:
start_time_time: My Start Time Text #renamed text
stylist_services: "" #hidden txet
I did almost the same thing as Brandon.
First, I wrote a helper function for the object that the errors will render for.
#Remove unnecessary attribute names in error messages
def exclude_att(attribute, error_msg)
if attribute.to_s == "Put attribute name you don't want to see here"
error_msg
else
attribute.to_s.humanize + " " + error_msg
end
end
Then, in the view that has the form being validated, I did:
(Note: this is HAML code not HTML, but the tags are still the same so you can clearly see what I'm doing)
%h3= "#{pluralize(#user.errors.count, 'error')} prohibited this user from being saved:"
%ul
- #user.errors.each do |att, error|
%li= exclude_att(att, error)
That did it for me, no gems or third-party plugins.
-Demitry

Resources