【问题标题】:How to show an error outside of a form in Rails如何在 Rails 中的表单之外显示错误
【发布时间】:2014-09-29 14:11:07
【问题描述】:

我想在我创建的视图/方法中显示错误消息。问题是我在模型中添加了错误,您可以在以下代码中看到:

errors.add :base, 'It can't be destroyed because some users use it'

但是在我尝试渲染的视图中,没有显示错误。

我复制了表单的错误呈现机制。 我必须制作一个表格或类似的东西来显示错误消息吗?

【问题讨论】:

    标签: ruby-on-rails error-handling


    【解决方案1】:

    确保两件事:

    1. 您在视图模板中有以下块:

      <%= @posts.errors.full_message.each |key, value| %> 
        # display value
      <% end %>
      
    2. 在您的控制器中分配错误消息:

      redirect_to posts_path, flash[:alert] = "It can't be destroyed because some users use it"
      

    【讨论】:

      【解决方案2】:

      您可以只使用flash 功能来解决错误。当您的控制器从您的模型收到错误时,请执行以下操作:

      redirect_to show_url(@post), alert: "It can't be destroyed because some users use it"
      

      【讨论】:

        【解决方案3】:

        当发生验证错误时,您应该能够在视图模板的任何位置添加错误消息。它看起来像这样:

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

        来源:http://guides.rubyonrails.org/active_record_validations.html#working-with-validation-errors

        【讨论】:

          【解决方案4】:

          假设您在狗 index 视图中更新单个狗,当您需要在没有 Javascript 和表单之外快速显示验证错误时,解决方案是将一系列错误(如单个错误)发送到部分错误布局并在那里遍历它们。

          请注意,这种方法不是传统的,并且有一些缺点。你需要从控制器redirect_to,因为renderwon't work well,所以你将刷新页面并冒泡(传播)到顶部。

          # dogs_controller.rb
          class DogsController
            def index
              @dogs = Dog.all
            end
          
            def update
              if dog.update
                # ...
              else
                flash[:danger] = dog.errors.full_messages
                redirect_to dogs_path
              end
            end
          end
          
          # app/views/layouts/_errors.html.haml
          - flash.each do |message_type, message|
            - if message.is_a?(Array)
              # show validation errors outside of form workaround
              - message.each do |msg|
                .alert.alert-danger= msg
            - else
              # usual error handler (from controller flash)
              = content_tag(:div, message, class: "alert alert-#{message_type}")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-16
            • 2012-12-18
            • 2013-05-26
            • 1970-01-01
            • 1970-01-01
            • 2018-12-20
            • 2020-08-12
            相关资源
            最近更新 更多