gpt4 book ai didi

ruby-on-rails - 设计自定义Flash消息

转载 作者:行者123 更新时间:2023-12-04 04:45:41 27 4
gpt4 key购买 nike

注册后,我想在我的Flash消息中访问current_user.username。我该怎么做呢?可以在devise.en.yml文件中完成吗?

最佳答案

我认为您必须覆盖注册 Controller 才能自定义Flash消息。

如果看一下devise.en.yml文件,可以看到使用了一些变量,例如%{resource}%{count}。通过查看原始注册 Controller ,您可以看到此代码(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

结尾

我将重写此 Controller 并添加此行
set_flash_message :notice, :signed_up, :username => resource.username if is_flashing_format?

然后在 devise.en.yml文件中,您应该可以使用类似的内容
devise:
registrations:
signed_up: 'oh hello %{username}'

告诉我那是否有效。

如果您需要有关如何重写Devise Controller 的提示,请查看 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

但是,请更新您的代码,以便我们找出问题所在。

关于ruby-on-rails - 设计自定义Flash消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6010407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com