我想在注册后访问我的flash消息中的current_user.username。我该怎么做呢?可以在devise.en.yml文件中完成吗?
答案 0 :(得分:20)
我认为您必须覆盖注册控制器才能自定义您的Flash消息。
如果您查看devise.en.yml文件,可以看到使用了%{resource}
或%{count}
等变量。通过查看原始注册控制器,您可以看到此代码(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
端
我会重写这个控制器并添加这一行
set_flash_message :notice, :signed_up, :username => resource.username if is_flashing_format?
然后在您的devise.en.yml
文件中,您应该可以使用类似的内容
devise:
registrations:
signed_up: 'oh hello %{username}'
告诉我这是否奏效。
如果您需要提示如何重写Devise控制器,请查看this
希望它有所帮助。
=====更新=====
我测试了它并且有效。
好的,如果我们想深入一点,我们可以查看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
但请更新您的代码,以便我们可以看到错误。