ruby-on-rails – 设计自定义flash消息

我想在注册后访问我的flash消息中的current_user.username.我该怎么做呢?可以在devise.en.yml文件中完成吗?
我认为您必须覆盖注册控制器才能自定义您的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

但请更新您的代码,以便我们可以看到有什么问题.

翻译自:https://stackoverflow.com/questions/6010407/devise-custom-flash-message

转载注明原文:ruby-on-rails – 设计自定义flash消息