Error messages from model in Rails 3.2 -
currently app includes following code to display error messages on view model.rb not updated code error_messages_for
deprecated in rails 3. can please suggest me how same in rails 3?? want logic in model.rb file , there should able display error msgs on view
excel_file.rb(model.rb)
#jus sample function def show_error(test_file) if test_file == 'upload test case' errors[:base] << "please upload excel sheet testsuite config sheet , testcases" elsif test_file == 'upload test data' errors[:base] << "please upload excel sheet test data" end end
sampleview.html.erb
#some code.. <span class='error'><%= error_messages_for (@excel_file) %></span> #some code..
application_helper.rb
def error_messages_for(*objects) html = "" objects = objects.map {|o| o.is_a?(string) ? instance_variable_get("@#{o}") : o}.compact errors = objects.map {|o| o.errors.full_messages}.flatten if errors.any? html << "<div id='errorexplanation'><ul>\n" errors.each |error| html << "<li>#{h error}</li>\n" end html << "</ul></div>\n" end html.html_safe end
you use https://github.com/rails/dynamic_form.
it provides functionality want.
update
you right, not in accordance rails 3.
you should this:
create shared partial
/app/views/shared/_error_messages.html.erb
<% if target.errors.any? %> <div id="errorexplanation"> <h2><%= pluralize(target.errors.count, "error") %> prohibited record being saved:</h2> <ul> <% target.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
and call this:
<%= render "shared/error_messages", :target => @excel_file %>
so why methods error_messages_for
, f.error_messages
removed? ryan bates says following:
the reason methods have been removed display of error messages needs customized , doing through old methods little bit cumbersome , not flexible having error message html inline have now. having html hand in views means can change display of error messages like.
source: http://asciicasts.com/episodes/211-validations-in-rails-3
update 2
this works custom validations same way
validate :show_error def show_error if test_file == 'upload test case' errors[:base] << "please upload excel sheet testsuite config sheet , testcases" elsif test_file == 'upload test data' errors[:base] << "please upload excel sheet test data" end end
Comments
Post a Comment