在 Ruby on Rails 中呈现验证错误 [英] Rendering validation errors in Ruby on Rails
本文介绍了在 Ruby on Rails 中呈现验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在模型中说任务,我有以下验证
validates_presence_of :subject, :project, :user, :status
如何使用其他控制器为这些验证呈现错误消息.
我正在使用的 CustomController 内部,
Task.create(hash)
在散列中传递 nil 值会出现以下错误,
ActiveRecord::RecordInvalid in CustomController#create验证失败:主题不能为空
控制器创建动作中的代码
@task = Task.create(hash)如果@task.valid?flash[:notice] = l(:notice_successful_update)别的flash[:error] = ""+ @task.errors.full_messages.map{|o|- "+ o + "</li>"}.join("") + "</ul>"结尾重定向到:返回
如何向用户呈现错误消息.
任务模型已经建立并呈现正确的消息.我想从插件中使用它的功能.
解决方案
这应该可行
<%= form_for(@task) do |f|%><% if @task.errors.any?%><div id="error_explanation"><h2><%=pluralize(@task.errors.count, "error") %>禁止保存此任务:</h2><ul><% @task.errors.full_messages.each 做 |msg|%><li><%=msg%></li><%结束%>
<%结束%><div class="actions"><%= f.submit %>
<%结束%>
In a model say Task, I have following validation
validates_presence_of :subject, :project, :user, :status
How do I render error messages for these validations using some other controller.
Inside CustomController I am using,
Task.create(hash)
passing nil values in hash gives following error,
ActiveRecord::RecordInvalid in CustomController#create
Validation failed: Subject can't be blank
Code in the controller's create action
@task = Task.create(hash)
if @task.valid?
flash[:notice] = l(:notice_successful_update)
else
flash[:error] = "<ul>" + @task.errors.full_messages.map{|o| "<li>" + o + "</li>" }.join("") + "</ul>"
end
redirect_to :back
How to render error messages to user.
Task model is already built and it renders proper messages. i want to use its functionalities from a plugin.
解决方案
This should work
<%= form_for(@task) do |f| %>
<% if @task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% @task.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这篇关于在 Ruby on Rails 中呈现验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文