Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.
I don't want to hack around rails' validation process and I feel there should be a way of fixing that.
One solution might be to change the i18n default error format:
Default is
format: %{attribute} %{message}
Try this.
I found this here.
Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.
The above code is from here
In your view
When you want to override the error message without the attribute name, simply prepend the message with ^ like so:
Just do it the normal way:
But display it like this instead
Returns
The localization method is definitely the "proper" way to do this, but if you're doing a little, non-global project and want to just get going fast - this is definitely easier than file hopping.
I like it for the ability to put the field name somewhere other than the beginning of the string:
Rails3 Code with fully localized messages:
In the model user.rb define the validation
In config/locales/en.yml
Related to the accepted answer and another answer down the list:
I'm confirming that nanamkim's fork of custom-err-msg works with Rails 5, and with the locale setup.
You just need to start the locale message with a caret and it shouldn't display the attribute name in the message.
A model defined as:
with the following
en.yml
:item.errors.full_messages
will display:instead of the usual
Name You can't create an item without a name