简体   繁体   中英

Rails validation error not including attribute name

I know I can fix this issue with i18n, which I will try to do if I have the time, but for a quicker fix I was curious: Is there a way to add the attribute name to a rails validation error? For example, I have the following in my model:

validates_presence_of :name

The validation error rendered is can't be blank . I'd prefer it to say Name can't be blank .

validates_presence_of :name, :format => { :message => "whatever you want" }

Use errors.full_messages :

<ul>
  <% @record.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>

Only -

validates_presence_of :name, :message => "Name can't be blank" 

for validates_presence_of , error-locale is - "can't be blank"; attribute/property name is prefixed during validation. You can override this by above. So, for your case, since property name is 'Name', error will automatically become "Name can't be blank". To override the property name for all validation, you can use human_attribute_name(http://apidock.com/rails/ActiveModel/Translation/human_attribute_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM