Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails - Reusing the error message partial view

Problem

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.

Remedy

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.

I want to know, Is that a correct way to do it? Or is there any other option?

like image 578
Vikrant Labde Avatar asked Aug 28 '13 10:08

Vikrant Labde


2 Answers

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.

like image 53
Marek Lipka Avatar answered Oct 25 '22 17:10

Marek Lipka


<%= 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.

like image 22
Rajarshi Das Avatar answered Oct 25 '22 16:10

Rajarshi Das