Rails errors style Customization

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.