加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:44:00 所属栏目:百科 来源:网络整理
导读:我们有一个表单,可以在我们的views / restaurants / show.html.erb中为某个餐厅提交评分.如果存在验证错误,我们会将其重定向回views / restaurants / show.html.erb,但不会显示验证消息.我们发现这是因为我们在RatingController创建操作中使用redirect_to(@r
我们有一个表单,可以在我们的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

同样,控制器动作可以设置闪存消息.最后,用户可能已将数据输入到输入字段中,我们希望它也可以通过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

根据您的设置,您可能需要也可能不需要将模型数据(例如订单)保存到会话中.我这样做的目的是将数据传回原始控制器,从而能够再次设置订单.

在任何情况下,为了显示实际的错误和flash消息,我做了以下(在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消息(如通知,警报等)将是字符串,但由于上述调用是错误,因此错误将是数组.to_a

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读