ruby-on-rails - 重定向后的验证消息

标签 ruby-on-rails validation redirect

我们有一个表格可以在我们的 views/restaurants/show.html.erb 中提交某个餐厅的评级。如果出现验证错误,我们将被重定向回 views/restaurants/show.html.erb,但不会出现验证消息。我们发现这是因为我们在 RatingController 创建操作中使用 redirect_to(@restaurant) 丢失了消息。但是我们如何在没有重定向的情况下返回?

谢谢!

最佳答案

这是我解决这个问题的方法。 (请注意,在接下来的内容中,我显然只包含了最相关的行。)

在模型中可能有多个验证,甚至可能有报告多个错误的方法。

class Order < ActiveRecord::Base
  validates :name, :phone, :email, :presence => true
  def some_method(arg)
    errors.add(:base, "An error message.")
    errors.add(:base, "Another error message.")
  end
end

同样, Controller Action 可以设置闪现消息。最后,用户可能已经在输入字段中输入了数据,我们希望它通过 redirect_to 持久化。也。
class OrdersController < ApplicationController
  def create
    @order = Order.new(params[:order])
    respond_to do |format|
      if @order.save
        session.delete(:order) # Since it has just been saved.
      else
        session[:order] = params[:order]  # Persisting the order data.

        flash[:notice] = "Woohoo notice!" # You may have a few flash messages
        flash[:alert] = "Woohoo alert!"   # as long as they are unique,
        flash[:foobar] = "Woohoo foobar!" # since flash works like a hash.

        flash[:error] = @order.errors.to_a # <-- note this line

        format.html { redirect_to some_path }
      end
    end
  end
end

根据您的设置,您可能需要也可能不需要将模型数据(例如订单)保存到 session 中。我这样做是为了将数据传回原始 Controller ,从而能够再次在那里设置订单。

无论如何,为了显示实际的错误和闪现消息,我做了以下操作(在 views/shared/_flash_messages.html.erb 中,但您可以在 application.html.erb 或其他对您的应用程序有意义的地方进行)。这要归功于那条线 flash[:error] = @order.errors.to_a
<div id="flash_messages">
  <% flash.each do |key, value|

    # examples of value: 
    # Woohoo notice!
    # ["The server is on fire."]
    # ["An error message.", "Another error message."]
    # ["Name can't be blank", "Phone can't be blank", "Email can't be blank"]

    if value.class == String # regular flash notices, alerts, etc. will be strings
      value = [value]
    end

    value.each do |value| %>
      <%= content_tag(:p, value, :class => "flash #{key}") unless value.empty? %>
    <% end %>
  <% end %>
</div><!-- flash_messages -->

需要明确的是,通知、警报等常规 flash 消息将是字符串,但错误将是数组,因为上述调用是 errors.to_a

关于ruby-on-rails - 重定向后的验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2819346/

相关文章:

python - 如何在 scrapy 中获取原始 start_url(在重定向之前)

ruby-on-rails - 更好的关联性能

ruby-on-rails - Rails Devise 检查用户是否未登录

javascript - 如何修复功能失调的分页?

c# - 将 DataAnnotations 与 Entity Framework 一起使用

forms - 使用 yup 和自定义验证验证 react-final-form 表单

ruby-on-rails - Rspec : PG::ConnectionBad: PQsocket() 无法获取套接字描述符

javascript - 欧芹远程验证

redirect - 提供重定向的 CDN?

PowerShell 在使用 tee-object 时删除控制台消息颜色