尝试从design登录时的错误消息没有显示在Rails 7.0应用程序中



我的application.html.erb中有一个rails 7.0应用程序

<body>
<%= yield %>
<div class="signin-container">
<div class="signin-container-inner">
<%- flash.each do |name, msg| -%>
<%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
<%- end -%>
</div>
</div>
</body>

当我访问登录页面并添加一些错误的电子邮件或密码时,错误消息不会显示。

由于Ruby on Rails 7使用:turbo_stream,我们需要进行一些修改以获得所需内容。

首先,我们为Devise:添加一个新的父控制器

# frozen_string_literal: true
# app/controllers/turbo_devise_controller.rb
class TurboDeviseController < ApplicationController
class Responder < ActionController::Responder
def to_turbo_stream
controller.render(options.merge(formats: :html))
rescue ActionView::MissingTemplate => e
if get?
raise e
elsif has_errors? && default_action
render rendering_options.merge(formats: :html, status: :unprocessable_entity)
else
redirect_to navigation_location
end
end
end
self.responder = Responder
respond_to :html, :turbo_stream
end

其次,我们还需要告诉Devise使用我们的新控制器,并添加一个类来处理我们的错误:

# frozen_string_literal: true
# app/config/initializers/devise.rb
# ! Create custom failure for turbo
class TurboFailureApp < Devise::FailureApp
def respond
if request_format == :turbo_stream
redirect
else
super
end
end
def skip_format?
%w(html turbo_stream */*).include? request_format.to_s
end
end
Devise.setup do |config|
...
config.parent_controller = 'TurboDeviseController'
config.navigational_formats = ['*/*', :html, :turbo_stream]
config.warden do |manager|
manager.failure_app = TurboFailureApp
end
...
end

就是这样。

更多信息:GoRails-如何使用Devise与Hotwire&Turbo.js

这里有一个解决方法,当同时使用Rails7、Hotwire、Turbo和Devise时会出现这个问题。通过将data:{turbo: false}与每个Devise表单一起传递,可以防止Turbo与Devise身份验证过程发生冲突。这应该允许Devise在Rails应用程序中使用Hotwire和Turbo的同时正常工作。

以下是如何在Devise表单上使用数据的示例:{turbo:false}:

<%= form_for(resource, as: resource_name, url: session_path(resource_name), data: {turbo: false}) do |f| %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Log in" %>
<% end %>

在本例中,data: {turbo: false}作为一个选项传递给form_for helper方法。这条消息告诉Turbo不要将其任何功能应用于此表单,这样可以防止与Devise的身份验证过程发生任何冲突。

最新更新