1

目前,我的应用程序包含以下代码,用于在 model.rb 的视图上显示错误消息,但它没有像error_messages_forRails 3 中已弃用的那样更新代码。谁能建议我如何在 Rails 3 中做同样的事情?我希望逻辑在 model.rb 文件中,从那里我应该能够在视图中显示错误消息

excel_file.rb(model.rb)

#jus some sample function
def show_error(test_file)
    if test_file == 'Upload Test Case'
      errors[:base] << "Please upload excel sheet with testsuite config sheet and testcases" 
    elsif test_file == 'Upload Test Data'
      errors[:base] << "Please upload excel sheet with 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 do |error|
      html << "<li>#{h error}</li>\n"
    end
    html << "</ul></div>\n"
  end
  html.html_safe
end
4

2 回答 2

2

您可以使用https://github.com/rails/dynamic_form

它提供了您想要的功能。

更新

你是对的,这不符合 Rails 3。

你可能应该做这样的事情:

创建共享部分

/app/views/shared/_error_messages.html.erb

<% if target.errors.any? %>  
<div id="errorExplanation">  
  <h2><%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:</h2>  
  <ul>  
  <% target.errors.full_messages.each do |msg| %>  
    <li><%= msg %></li>  
  <% end %>  
  </ul>  
</div>  
<% end %>

并这样称呼它:

<%= render "shared/error_messages", :target => @excel_file %>

那么为什么这些方法都被error_messages_for删除f.error_messages了呢?瑞安贝茨说:

删除这些方法的原因是错误消息的显示通常需要自定义,并且通过旧方法执行此操作有点麻烦,并且不像我们现在将错误消息 HTML 内联那样灵活。将 HTML 提交到视图中意味着我们可以随意更改错误消息的显示。

来源:http ://asciicasts.com/episodes/211-validations-in-rails-3

更新 2

这同样适用于自定义验证

validate :show_error

def show_error
  if test_file == 'Upload Test Case'
    errors[:base] << "Please upload excel sheet with testsuite config sheet and testcases" 
  elsif test_file == 'Upload Test Data'
    errors[:base] << "Please upload excel sheet with test data" 
  end
end
于 2013-05-15T10:01:07.207 回答
0

解决方案:

创建共享部分

app/views/common/_error_messages.html.erb:

<% if target.errors.any? %>  
<div id="errorExplanation">  
  <h2><%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:</h2>  
  <ul>  
  <% target.errors.full_messages.each do |msg| %>  
    <li><%= msg %></li>  
  <% end %>  
  </ul>  
</div>  
<% end %>

并这样称呼它:(在sampleview.html.erb中)

<% if @excel_file %>
    <%= render "common/error_messages", :target => @excel_file %>
<% end %>

提出 if 条件以避免错误 NoMethodError:Undefined method 'errors' in target.errors.any?。这样可以避免页面抛出此错误,并且仅在存在 target(@excel_file) 实例时才呈现部分视图。

这同样适用于自定义验证

在 app/model 的 excel_file.rb(model.erb) 中:

def show_error if test_file == '上传测试用例'错误[:base] << "请上传带有测试套件配置表和测试用例的excel表" elsif test_file == '上传测试数据'错误[:base] << "请上传excel带有测试数据的表” end end

这非常有效!现在我可以正确收到错误通知了:)

于 2013-05-17T06:53:25.753 回答