I have user.errors which gives all errors in my controller. So, i have the field :user_login which has its error(s). How can i get full error messages from user.errors ONLY for that field?
I can get just text of this field like that:
user.errors[:user_login] # Gives that 'can't be empty'
But i really want to do something like that
user.errors.get_full_message_for_field[:user_login] # 'Your login can't be empty'
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).
Have a look at full_message here:
http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_message
A bit verbose but you may be able to do something like:
user.errors.full_message(:user_login, user.errors[:user_login])
We can get the error message of particular field by using
<%= resource.errors.full_messages_for(:email).join("") %>
output : Email cant be blank
If you want to check the particular field has error or not then check it by using
resource.errors.include?(:email)
output : true/false
Here is the code snippet for displaying only the first error for each field.
<!-- Display only first error for each field --->
<% entity.attributes.keys.each do |key| %>
<% if entity.errors.full_messages_for(key.to_sym).length > 0 %>
<li><%= entity.errors.full_messages_for(key.to_sym).first %></li>
<% end %>
<% end %>
Related
I've successfully created my he.yml to localize my model's attributes names,
example:
attributes:
vendor:
name: שם ספק
counter_number: מספר חשבונית
phone: טלפון
address: כתובת
Now, displaying labels in forms using simple_form's f.input, displays it correctly, the translated value of each attribute.
the problem is, displaying errors after validation, using
<% #vendor.errors.each do |attribute, error| %>
|attribute| for error "counter_number" for example, is displayed: "counter_number".
not the translated one at the locale file [which as i mentioned previously, configured and loaded successfully].
I appended errors in a ul.errors, as shown in this screenshot:
Thanks in advance.
You can do something like this:
#vendor.errors.messages do |attribute, errors|
translated_attribute = Vendor.human_attribute_name(attribute)
errors = errors.join(", ")
end
I've tested this with my User model:
The following is just an example to complete your provided code.
<% #vendor.errors.each do |attribute, error| %>
<strong><%= t("activerecord.attributes.#{#vendor.class.to_s.underscore}.#{attribute}") %>:</strong>
<%= error.messages.to_sentence %>
<% end %>
Maybe there is an easier approach than this.
My error messages are not showing automatically, so I decided to use flash as a workaround. This is what I'm doing
Controller:
flash[:notice] = #post.errors.full_messages
View:
<%= flash[:notice] %>
Then, I get this ugly error message on my view.
["Content can't be blank", "Content is too short (minimum is 10 characters)"]
But at least, the user successfully gets the error message. Now I need to customize the error message and make it look a little bit more pretty. I guess I could parse each error sentence into some local variables and show them (is there a more sophisticated way?). However, I don't know how to customize the error message. For example, "Content can't be blank" should be changed to "You left the content blank". Where can I fix this?
What happens is that when #post contains some validation errors doing #post.errors.full_messages returns an array of errors that happened during validation.
To display them nicely you might want to do something like
<%- flash[:notice].each do |error| %>
<%= error %>
<% end %>
EDIT
Whoops I misread the question.
These errors are validation errors in your model where you have the validations like
validates you can pass custom messages like so
validates :content, :presence => { :message => "You left the content blank" }
Update: check this link out for the options you have
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates
When you set a validation message in paperclip, such as
validates_attachment_presence, :image, :message => 'xxxx'
The custom message comes automatically prefixed with the name of the field, even though it has been overwritten with the :message . How do you totally override the message and make it totally custom?
Edit: typo
Not a real solution but a Easy one is to skip paperclip validation and write custom one.
validate :check_content_type
def check_content_type
if !['image/jpeg', 'image/gif','image/png'].include?(self.image_content_type)
errors.add_to_base("Image '#{self.image_file_name}' is not a valid image type") # or errors.add
end
end
I hope it can help
You actually want to do this inside your view rather than your model and it's actually quite straight forward. We're just going to loop through the errors, and when the one for your attachment comes up we'll ignore the field name:
<ul>
<% #myObject.errors.keys.each do |field| %>
<% #myObject.errors[field].each do |msg| %>
<% if field == :image_file_name %>
<li><%= msg %></li>
<% else %>
<li><%= field.to_s + " " + msg %></li>
<% end %>
<% end %>
<% end %>
</ul>
Replacing #myObject with the name of your model that should display only the message set to your attachment validation errors. This is just a simple example that displays them inline with the rest, but of course you could do anything you like with the messages. It's important to keep the name of the field that had the error in case you want to program any logic thats specific to its failure without having to rely on the error message staying exactly the same forever.
It's standard Rails behavior to show include the attribute name before the validation errors. You have a few options to work around this behavior:
Make your error message OK to have the attribute name prepended :)
Use a different error message formatter. It's pretty easy to write your own helper to iterate through an #object.errors and wrap messages in HTML tags. I prefer to use the error messages in-line near the fields so we always skip the attribute name.
Custom validation which adds the errors to base. This is easy, but wrong, since you're suggesting there's a validation error on a field. Still may solve your problem.
Override humanized_attribute_name for that attribute to hide it. humanized_attribute_name is probably used elsewhere, so this may cause other issues.
.
HumanizedAttributesOverride = {
:image => ""
}
def self.human_attribute_name(attr)
HumanizedAttributesOverride[attr.to_sym] || super
end
I don't know if it's just a typo inside your question, but it should be:
validates_attachment_presence :image, :message => 'xxxx'
And I would not use :message to add a custom error message, but put it inside a locales file.
In my Rails CREATE controller for a model, if the name of the record already exists, via JS I'm outputting the following response:
<%=#space.errors%>
Which outputs:
permissionsis invalidnameThis project name is already in use
In the model I have:
validates_uniqueness_of :name :message => 'This project name is already in use'
How do I get rid of the noise: "permissionsis invalidname" for the life of me I can't find it in the docs? Apologies if I'm missing something hugely obvious.
The issue is that you are actually returning the array containing all the error objects.
What you actually want is:
<ul>
<% #space.errors.full_messages.each do |msg| %>
<li><%=h msg %></li>
<% end %>
</ul>
This will give you a list of the errors.
I'm also pretty sure there's a nicer way to do this (i.e. some sort of helper built in to rails), but I haven't been able to find it in the docs for rails 3.
I'm creating a Rails app, and I have a model called User. In this model I have a boolean value called isagirl. A user must specify if it is a girl or not, which is done by two radio buttons. In my model I have this:
validates_presence_of :isagirl, :message => "You must be either a Boy or a Girl. If not, please contact us."
However, when I don't specify a sex, I'm seeing this:
Isagirl You must be either a Boy or a Girl.
as an error message. The problem is that 'Isagirl' must not be there in the error message. How can I disable that? And no, using CSS to hide it is no option.
Thanks
The way that I do this is to output the message without the field name. For example, I have a partial that outputs the error messages after validation fails.
<ul>
<% errors.each do |attribute, message| -%>
<% if message.is_a?(String)%>
<li><%= message %></li>
<% end %>
<% end -%>
</ul>
Notice that this does not output the attribute. You just need to make sure that all your messages makes sense without an attribute name.
In one of my projects I was using custom-err-msg plugin. With it when you specify error message this way:
:message => "^You must be either a Boy or a Girl. If not, please contact us."
(notice ^ at the begining) it won't print attribute name when printing errors. And you can use standard error_messages or error_messages_for helpers.
I don't know how to omit the attribute name in the validates_presence_of function (it can be painful without dirty hacking) but I would use validate function to achieve what you want:
protected
def validate
errors.add_to_base("You must be either a Boy or a Girl. If not, please contact us.") if params[:isagirl].blank?
end
I used specifically method blank? here because validates_presence_of is using blank? for the test you should get this same behavior.
add_to_base is adding general error messages that are not related to the attributes and this saves you from hacking the view.
I recommend using the errors.add_to_base option. Without knowing what your layout looks like, that's going to be the simplest way to get a plain error message to appear.