I would like to access current_user.username in my flash messa开发者_开发问答ge after registering. How do I go about doing this? Can this be done in the devise.en.yml file?
I think you have to overwrite registration controller in order to customize your flash message.
If you take a look at devise.en.yml file, you can see that some variables like %{resource}
or %{count}
are used. By taking a look at original registration controller, you can see this code ( check 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 should be able to use something like that
devise:
registrations:
signed_up: 'oh hello %{username}'
Tell me if that worked.
If you need hint on how to rewrite Devise controller, take a look at this
Hope it helped.
===== UPDATE =====
I tested it and it worked.
Okay 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 we can see what's wrong.
精彩评论