简体   繁体   中英

Rails: Changing Error Messages

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

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