I was trying to reuse the Error Message block in my Views.
Below was the block written in positions/_error_messages.html.erb
<% if @position.errors.any? %>
  <div id="error_explanation">
   <div class="alert alert-error">
     The form contains <%= pluralize(@position.errors.count, "error") %>.
   </div>
   <ul>
    <% @position.errors.full_messages.each do |msg| %>
    <li>* <%= msg %></li>
   <% end %>
   </ul>
 </div>
<% end %>
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.
I have created one erb in shared folder shared/_error_messages.html.erb and wrote the below code.
<% def error_message(active_object) %>
 <% if active_object.errors.any? %>
  <div id="error_explanation">
   <div class="alert alert-error">
    The form contains <%= pluralize(active_object.errors.count, "error") %>.
   </div>
   <ul>
    <% active_object.errors.full_messages.each do |msg| %>
     <li>* <%= msg %></li>
    <% end %>
   </ul>
  </div>
 <% end %>
<% end %>
and then in view file. positions/new.html.erb I wrote the below code
<div id="errorbox"> 
 <%= render "shared/error_messages" %>
 <%= error_message(@position) %>
</div>
It means now I can use the same code in all my Create and Update operations.
No, defining methods in views is not correct way to do it. I think you should rather substitute @position from your first partial with local variable named in more generic way, for example object and render this partial with:
<%= render 'shared/error_messages', object: @position %>
which passes @position as local variable object to the partial. 
<%= render partial: 'shared/error_messages', locals: {position: @position} %>
Now in your partial _error_messages.html.erb in the shared folder you can use the position variable.
Refer to http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html for more help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With