DEV Community

Cover image for How to use Devise with turbo in Rails 7
Efo Coder
Efo Coder

Posted on

How to use Devise with turbo in Rails 7

In Rails 7, hotwire's turbo intercepts form actions and submits them over the wire.

Currently, Devise gem does not support this action, hence needs a little tweaking to function well.

NB: This tutorial assumes you have installed and configured Devise gem already.

First let's create a controller, I will name mine app/controllers/turbo_devise_user_controller.rb

class TurboDeviseUserController < ApplicationController
 class Responder < ActionController::Responder
    def to_turbo_stream
      controller.render(options.merge(formats: :html))
          rescue ActionView::MissingTemplate => error
      if get?
        raise error
      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
Enter fullscreen mode Exit fullscreen mode

The above controller will make Devise responds to turbo and rendering templates. But of course, this won't happen without a modifying our devise initializer, which is located at config/initializers/devise.rb

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|
  ...
  # Configure the parent class to the custom controller.
  config.parent_controller = 'TurboDeviseUserController'
  config.navigational_formats = ['*/*', :html, :turbo_stream]


  # Warden configuration
  config.warden do |manager|
    manager.failure_app = TurboFailureApp
  end

...
end
Enter fullscreen mode Exit fullscreen mode

That's it! Now start you rails app and keep coding!!.

Discussion (0)