Design a custom flash message

I want to access the current username in my flash message after registering. How can I do it? Can this be done in the devise.en.yml file?

+8
ruby-on-rails
source share
1 answer

I think you need to overwrite the registration controller in order to configure the flash message.

If you look at the devise.en.yml file, you will see that some variables like %{resource} or %{count} . If you look at the original registration controller, you can see this code ( here)

 # POST /resource def create build_resource(sign_up_params) if resource.save yield resource if block_given? if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_flashing_format? sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource respond_with resource end 

end

I would rewrite this controller and add this line

 set_flash_message :notice, :signed_up, :username => resource.username if is_flashing_format? 

Then in your devise.en.yml file you can use something like this

 devise: registrations: signed_up: 'oh hello %{username}' 

Tell me if it worked.

If you need a hint on how to rewrite a devise controller, check out this

Hope this helped.

===== UPDATE =====

I tested it and it worked.

So, if we want to go deeper, we can check lib/devise/controllers/internal_helpers.rb :

 # Sets the flash message with :key, using I18n. By default you are able # to setup your messages using specific resource scope, and if no one is # found we look to default scope. # Example (i18n locale file): # # en: # devise: # passwords: # #default_scope_messages - only if resource_scope is not found # user: # #resource_scope_messages # # Please refer to README or en.yml locale file to check what messages are # available. def set_flash_message(key, kind, options={}) #:nodoc: options[:scope] = "devise.#{controller_name}" options[:default] = Array(options[:default]).unshift(kind.to_sym) options[:resource_name] = resource_name message = I18n.t("#{resource_name}.#{kind}", options) flash[key] = message if message.present? end 

But please update your code so that we can understand what is wrong.

+19
source share

All Articles