<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: field code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Mon, 06 Oct 2008 09:42:15 GMT</pubDate>
    <description>DZone Snippets: field code</description>
    <item>
      <title>Putting the errors in the right place</title>
      <link>http://snippets.dzone.com/posts/show/3403</link>
      <description>The idea is to display the error near the field instead of in global area at the top of the page.&lt;br /&gt;Simple&#8230; first go into your view and delete the&lt;br /&gt;&lt;code&gt;&lt;br /&gt;error_messages_for &#8216;object&#8217;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Then stick this in your application helper.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# application_helper.rb&lt;br /&gt;def error_for(object, method = nil, options={})&lt;br /&gt;  if method&lt;br /&gt;    err = instance_variable_get("@#{object}").errors.on(method).to_sentence     rescue instance_variable_get("@#{object}").errors.on(method)&lt;br /&gt;  else&lt;br /&gt;     err = @errors["#{object}"] rescue nil&lt;br /&gt;  end&lt;br /&gt;  options.merge!(:class=&gt;&#8217;fieldWithErrors&#8217;,&lt;br /&gt;          :id=&gt;"#{[object,method].compact.join(&#8217;_')}-error",&lt;br /&gt;:style=&gt;(err ? #{options[:style]}":"#{options[:style]};display: none;")&lt;br /&gt;   )&lt;br /&gt; content_tag("p",err || "", options )     &lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Then in your form view, add an &#8216;error_for&#8217; call wherever you need one&#8230;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# _form.rhtml&lt;br /&gt;  &lt;p&gt;&lt;label for="code_project_name"&gt;Name&lt;/label&gt;&lt;br /&gt;  &lt;%= text_field &#8216;code_project&#8217;, &#8216;name&#8217;  %&gt;&lt;br /&gt;  &lt;%= error_for &#8216;code_project&#8217;, &#8216;name&#8217; %&gt;&lt;/p&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;If the model fails a validation test, then it will show the message right next to the field that caused the validation problem.&lt;br /&gt;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&#8217;t correspond to a model attribute.</description>
      <pubDate>Thu, 01 Feb 2007 14:06:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3403</guid>
      <author>Mickael (Mickael)</author>
    </item>
  </channel>
</rss>
