Generally, the error message on the rails page is put in the header with error_message_for. the following error message is generated:
In this way, all the error messages will be displayed soon. However, there is a disadvantage, that is, the flexibility is too poor. It seems that error_message_for can quickly build a curd (add, delete, modify, and query) application just like rails's scaffold, but its customization is not high.
Fortunately, rails has a strong scalability. You don't like a method in it. You can evenSource codeChanged (of course this is not recommended...), so you only have to do it yourself ..
Read the source code:
# Returns the errors object that holds all information about attribute error messages. Def errors @ errors | = errors. New (Self) End
This sentence is enough: Each activerecord instance has an errors method. This @ errors is the basis for processing and encapsulating all other error information in rails.
I wrote a method to extract the field error information of each model to the DIV, and added the Chinese method to it, which is very simple ..
Module applicationhelper def error_div (model, field, field_name) return unless Model Field = field. is_a? (Symbol )? Field. to_s: field errors = model. errors [field] Return unless errors % Q (<Div class = "errors" >#{ errors. is_a? (Array )? Errors. Map {| E | field_name + e}. Join (","): field_name <errors} </div>) end
Demo:
Validation:
Class post <activerecord: Base validates_presence_of: title,: Message => "cannot be blank" validates_length_of: title,: In => 2 .. 10,: Message => "incorrect length" End
View:
<% Form_for (@ post) Do | f |%> <p> <% = f. label: Title %> <br/> <% = f. text_field: Title %> <% = sanitize (error_div (@ post,: title, "title") %> </P> <p> <% = f. label: Description %> <br/> <% = f. text_area: Description %> </P> <p> <% = f. submit 'create' %> </P> <% end %>
Effect 1:
Effect 2: