8
我想在注册后访问我的Flash消息中的current_user.username。我如何去做这件事?这可以在devise.en.yml文件中完成吗?设计自定义Flash消息
我想在注册后访问我的Flash消息中的current_user.username。我如何去做这件事?这可以在devise.en.yml文件中完成吗?设计自定义Flash消息
我认为你必须改写注册控制器来定制你的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
末
我想改写这个控制器并在devise.en.yml
文件中添加此行
set_flash_message :notice, :signed_up, :username => resource.username if is_flashing_format?
然后,你应该可以使用类似的东西
devise:
registrations:
signed_up: 'oh hello %{username}'
告诉我,如果这工作。
如果您需要提示如何改写设计控制器,看看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
不过,请更新您的代码,所以我们可以看到什么是错的。
我运行rails g controller注册并复制并粘贴到原始设计代码中。然后我按照你的建议和devise.en.yml文件修改了相应的行。我得到这个错误:在“注册完成,%{username}”({:resource_name =>:user}给出)中缺少插值参数 – chief 2011-05-15 20:32:07
我更新了我的帖子。我尝试了我的建议,并为我工作。 – Lucas 2011-05-15 21:06:39
嗯重新读你的评论,我觉得你忘了告诉Rails使用你的新控制器注册。请遵循以下步骤:在config/routes.rb中将:controllers => {:registrations =>“registrations”}添加到您的devise_for root。 (再次看到[教程](https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password)) – Lucas 2011-05-15 21:13:15