Rails 如何在 respond_with 之后显示即显消息

Rails how to show flash messages after respond_with

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

    # 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? returns 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 消息,它也可以正常工作,但我不喜欢这种方法。

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

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

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

这也有效

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