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