title: Ruby On Rails - Reusing the error message partial view
body: <h1>Problem</h1>
  
  <p>I was trying to reuse the Error Message block in my Views. </p>
  
  <p>Below was the block written in positions/_error_messages.html.erb</p>
  
  <pre class="lang-rb prettyprint-override"><code>&lt;% if @position.errors.any? %&gt;
    &lt;div id="error_explanation"&gt;
     &lt;div class="alert alert-error"&gt;
       The form contains &lt;%= pluralize(@position.errors.count, "error") %&gt;.
     &lt;/div&gt;
     &lt;ul&gt;
      &lt;% @position.errors.full_messages.each do |msg| %&gt;
      &lt;li&gt;* &lt;%= msg %&gt;&lt;/li&gt;
     &lt;% end %&gt;
     &lt;/ul&gt;
   &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>The problem was I have to created similar partial view in every Model which is kind of repeating the same code with different object i.e. @user, @client etc.</p>
  
  <h1>Remedy</h1>
  
  <p>I have created one erb in shared folder shared/_error_messages.html.erb and wrote the below code.</p>
  
  <pre class="lang-rb prettyprint-override"><code>&lt;% def error_message(active_object) %&gt;
   &lt;% if active_object.errors.any? %&gt;
    &lt;div id="error_explanation"&gt;
     &lt;div class="alert alert-error"&gt;
      The form contains &lt;%= pluralize(active_object.errors.count, "error") %&gt;.
     &lt;/div&gt;
     &lt;ul&gt;
      &lt;% active_object.errors.full_messages.each do |msg| %&gt;
       &lt;li&gt;* &lt;%= msg %&gt;&lt;/li&gt;
      &lt;% end %&gt;
     &lt;/ul&gt;
    &lt;/div&gt;
   &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>and then in view file. positions/new.html.erb I wrote the below code</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;div id="errorbox"&gt; 
   &lt;%= render "shared/error_messages" %&gt;
   &lt;%= error_message(@position) %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>It means now I can use the same code in all my Create and Update operations.</strong></p>
  
  <h2>I want to know, Is that a correct way to do it? Or is there any other option?</h2>