简体   繁体   中英

Flash messages not showing on update error with devise

I have devise and have added in username to the registration process. Ive also added in validations for username presence and length inside the mdoel.

On sign up if I don't put a Username in the validation kicks in and the flash message appears but on Edit User if i don't put a Username the validation kicks in but no flash appears. I have flash in 'layout/application' So it is present on every page.

Here is a helper method i have :

    module DeviseHelper
      def devise_error_messages!
        if resource.errors.full_messages.any?
          flash.now[:danger] = resource.errors.full_messages.to_sentence
        end
        return ''
      end
    end

Any ideas would be great thanks

Devise error helper method overwrites only for design related changes see the devise error helper method

module DeviseHelper
  def devise_error_messages!
    return "" if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t("errors.messages.not_saved",
                      count: resource.errors.count,
                      resource: resource.class.model_name.human.downcase)

    html = <<-HTML
    <div id="error_explanation">
      <h2>#{sentence}</h2>
      <ul>#{messages}</ul>
    </div>
    HTML

    html.html_safe
  end

   def devise_error_messages?
     !resource.errors.empty?
   end
end

Ok so i went and had look at the code for the update action in the registrations controller and found that i could add code to set the flash after its failed to update.

def update
      self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
      prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
      resource_updated = update_resource(resource, account_update_params)
      yield resource if block_given?
      if resource_updated
        if is_flashing_format?
          flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
            :update_needs_confirmation : :updated
          set_flash_message :notice, flash_key
        end
        bypass_sign_in resource, scope: resource_name
        respond_with resource, location: after_update_path_for(resource)
      else
        flash.now[:danger] = resource.errors.full_messages.to_sentence <<<< RIGHT HERE
        clean_up_passwords resource
        set_minimum_password_length
        respond_with resource
      end
    end

Here is the code incase anyone else has this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM