【问题标题】:Rails how to show flash messages after respond_withRails如何在respond_with之后显示flash消息
【发布时间】:2016-07-29 10:03:50
【问题描述】:

在活动管理员中,我必须覆盖设计密码控制器以在密码令牌过期时显示错误。默认情况下,如果令牌过期,它不会显示任何错误。下面是我要覆盖的方法

    # PUT /resource/password
  def update
    self.resource = resource_class.reset_password_by_token(resource_params)
    yield resource if block_given?

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
        set_flash_message(:notice, flash_message) if is_flashing_format?
        sign_in(resource_name, resource)
      else
        set_flash_message(:notice, :updated_not_active) if is_flashing_format?
      end
      respond_with resource, location: after_resetting_password_path_for(resource)
    else
      set_minimum_password_length
      respond_with resource
    end
  end

如果resource.errors.empty? 返回 false,则不会设置任何闪烁消息。 为了抛出错误异常,我做了以下操作:

ActiveAdmin::Devise::PasswordsController.class_eval do
  def update
    super
    if resource.errors.any?
      flash[:notice] = resource.errors.full_messages.to_sentence
    end
  end
end

使用上面的代码,错误现在是可见的,但不是在同一个页面加载时。但是,它显示在下一个视图中。如果我从设计密码控制器复制代码并在“respond_with”之前的else块中添加flash消息,它也可以正常工作,但我不喜欢这种方法。

有没有办法在不从设计控制器复制整个方法的情况下显示 Flash 消息?

【问题讨论】:

  • 您是否尝试过使用 flash.now?
  • flash.now 根本没有显示任何错误。

标签: ruby-on-rails devise activeadmin flash-message


【解决方案1】:

在更新操作的第二行有以下内容:

yield resource if block_given?

这意味着您可以将一个块传递给该方法,如下所示:

def update
  super do |resource|
    if resource.errors.any?
      flash[:notice] = resource.errors.full_messages.to_sentence
    end
  end
end

【讨论】:

    【解决方案2】:

    这也有效

    def create
     @user = User.new(params[:user])
    
     respond_to do |format|
     if @user.save
      flash[:notice] = 'User was successfully created.'
      format.html { redirect_to(@user) }
      format.xml { render xml: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.xml { render xml: @user.errors, status: :unprocessable_entity           }
     end
     end
     end
    

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2014-01-28
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多