Ruby On Rails - Reusing the error message partial view -
problem
i trying reuse error message block in views.
below block written in positions/_error_messages.html.erb
<% if @position.errors.any? %> <div id="error_explanation"> <div class="alert alert-error"> form contains <%= pluralize(@position.errors.count, "error") %>. </div> <ul> <% @position.errors.full_messages.each |msg| %> <li>* <%= msg %></li> <% end %> </ul> </div> <% end %>
the problem have created similar partial view in every model kind of repeating same code different object i.e. @user, @client etc.
remedy
i have created 1 erb in shared folder shared/_error_messages.html.erb , wrote below code.
<% def error_message(active_object) %> <% if active_object.errors.any? %> <div id="error_explanation"> <div class="alert alert-error"> form contains <%= pluralize(active_object.errors.count, "error") %>. </div> <ul> <% active_object.errors.full_messages.each |msg| %> <li>* <%= msg %></li> <% end %> </ul> </div> <% end %> <% end %>
and in view file. positions/new.html.erb wrote below code
<div id="errorbox"> <%= render "shared/error_messages" %> <%= error_message(@position) %> </div>
it means can use same code in create , update operations.
i want know, correct way it? or there other option?
no, defining methods in views not correct way it. think should rather substitute @position
first partial local variable named in more generic way, example object
, render partial with:
<%= render 'shared/error_messages', object: @position %>
which passes @position
local variable object
partial.
Comments
Post a Comment