DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Putting The Errors In The Right Place

Mickael  Gerard user avatar by
Mickael Gerard
·
Feb. 01, 07 · · Code Snippet
Like (0)
Save
Tweet
555 Views

Join the DZone community and get the full member experience.

Join For Free
The idea is to display the error near the field instead of in global area at the top of the page.
Simple… first go into your view and delete the

error_messages_for ‘object’


Then stick this in your application helper.


# application_helper.rb
def error_for(object, method = nil, options={})
  if method
    err = instance_variable_get("@#{object}").errors.on(method).to_sentence     rescue instance_variable_get("@#{object}").errors.on(method)
  else
     err = @errors["#{object}"] rescue nil
  end
  options.merge!(:class=>’fieldWithErrors’,
          :id=>"#{[object,method].compact.join(’_')}-error",
:style=>(err ? #{options[:style]}":"#{options[:style]};display: none;")
   )
 content_tag("p",err || "", options )     
end


Then in your form view, add an ‘error_for’ call wherever you need one…


# _form.rhtml
  

<%= text_field ‘code_project’, ‘name’ %> <%= error_for ‘code_project’, ‘name’ %>

If the model fails a validation test, then it will show the message right next to the field that caused the validation problem. Also note that if you define an instance variable called @errors containing a hash of field_names and messages, they will also be used. This is handy for those form fields that don’t correspond to a model attribute.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Don't Underestimate Documentation
  • Counting Faster With Postgres
  • How to Handle Early Startup Technical Debt (Or Just Avoid it Entirely)
  • What Do Great Engineering Managers Need To Know About Compensation and Equity?

Comments

Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo