如何在 Rails 中显示错误通知? [英] how to display errors notice in Rails?
本文介绍了如何在 Rails 中显示错误通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型中有以下代码:
Hi I have the following code in my model:
class Product < ActiveRecord::Base
before_destroy :check_tasks
has_many :tasks, :order => 'created_at DESC'
validates :name, :presence => true
belongs_to :sprint
validates :sprint_id, :presence => true
def check_tasks
if self.tasks.any?
errors.add_to_base "Product has tasks and cannot be destroyed."
return false
end
end
end
当我在列出所有产品的产品视图中时,我想在视图顶部显示错误消息,每次有人尝试删除具有链接到它的任务的产品时.我希望显示消息:产品有任务且无法销毁.
When I am in the product view which lists all the products, I would like to display the error message on the top of the view, every time someone tries to delete a product which has tasks linked to it. I want the message: Product has tasks and cannot be destroyed displayed.
我应该在下面的视图中放入什么代码?该视图是产品视图,位于 views/products 文件夹中.
What code should I put in the view below? The view is the product view, which is in the views/products folder.
谢谢!!!
<h1>Listing products</h1>
<%= link_to 'New Product', new_product_path %>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Sprint</th>
<th></th>
<th></th>
<th></th>
</tr>
<% if not @messages_rendered -%>
<% if flash[:error] -%>
<p class='error'><%=h flash[:error] %></p>
<% end -%>
<% if flash[:notice] -%>
<p class='notice'><%=h flash[:notice] %></p>
<% end -%>
<% end -%>
<% @messages_rendered = true -%>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.sprint.name %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
推荐答案
尝试将其放入您的 product_controller 中:
Try putting this in your product_controller:
def destroy
...
flash[:error] = @product.errors.full_messages.join(' ')
...
end
这篇关于如何在 Rails 中显示错误通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文