how to display errors notice in Rails?

有些话、适合烂在心里 提交于 2019-12-25 02:21:56

问题


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.

What code should I put in the view below? The view is the product view, which is in the views/products folder.

Thanks!!!

<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 />

回答1:


Try putting this in your product_controller:

def destroy
  ...
  flash[:error] = @product.errors.full_messages.join(' ')
  ...
end


来源:https://stackoverflow.com/questions/8545887/how-to-display-errors-notice-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!