Rails / Devise – 使用link_to自定义flash消息(devise.en.yml)
我想在devise.en.yml文件中自定义devise提供的以下flash msg:
devise: failure: unconfirmed: 'You have to confirm your account before continuing.'
使用ruby代码以获取new_user_confirmation_path的链接。
换句话说,我希望我的flash消息显示如下:
'You have to confirm your account before continuing. Didn't receive confirmation instructions?'
哪里’没有收到确认指示?’ 是new_user_confirmation_path的链接。
我想知道我是否可以在不编辑用户控制器的情况下执行此操作,因为默认情况下Devise不提供它。
感谢您的回答!
new_user_confirmation_path
是一个等同于https://stackoverflow.com/users/confirmation/new
的静态URL
所以你可以在devise.en.yml文件中执行此操作:
devise: failure: unconfirmed: "You have to confirm your account before continuing. Didn't receive confirmation instructions?"
在显示闪存的控制器操作中,确保你有.html_safe
例如flash[:error].html_safe
在我的一个应用程序中,我正在使用Devise和CanCan。 我在我的应用程序控制器中使用类似以下内容的方法从CanCan的错误中解救出来。
rescue_from CanCan::AccessDenied do |exception| if current_user flash[:error] = exception.message redirect_to root_url else flash[:error] = t("devise.failure.unauthenticated") redirect_to new_user_session_path end end
也许你可以做类似的事情并从Devise拯救? 您的Flash消息可能是这样的:
flash[:error] = t("devise.failure.unconfirmed") + link_to "Didn't receive confirmation instructions?", new_user_confirmation_path
如果需要,更好的是将“没有收到……”放在它自己的翻译yml中。
我认为Rails 3和Rails 4为Devise flash消息添加所需链接和其他信息的正确方法是编写自己的Devise::FailureApp
:
# lib/custom_failure.rb class CustomFailure < Devise::FailureApp def i18n_options(options) path = Rails.application.routes.url_helpers.new_user_confirmation_path link = ActionController::Base.helpers.link_to(I18n.t('.unconfirmed_link_text', options), path) super(options).merge(new_user_confirmation_link: link) end end
并为翻译添加插值:
devise: failure: unconfirmed: You have to confirm your account before continuing.%{new_user_confirmation_link} unconfirmed_link_text: Didn't receive confirmation instructions?
不要忘记添加到config/initializers/devise.rb
:
config.warden do |manager| manager.failure_app = CustomFailure end
如果我理解把问题放在代码的位置上(’设计……你必须放在我们的视图中,你想要显示这个消息。
例如devise/new.erb
:
<%= t('devise.failure.unconfirmed', :confirm_link => link_to( t('devise.failure.confirm_link_text'), new_user_confirmation_path).html_safe ) unless user.confirmed %>
您也可以在您的设计特定布局中执行此操作: app/views/layouts/devise.html.slim
- flash.each do |type, message| - if ['alert', 'error', 'notice'].include?(type.to_s) .alert-box class=type => message - case message - when t('devise.failure.unauthenticated') = link_to "Forgot your password?", new_password_path(resource_name) - when t('devise.failure.unconfirmed') = link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) - when t('devise.failure.locked') - if resource_class.unlock_strategy_enabled?(:email) = link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name)