Login flow with Hotwire

513 Views Asked by At

I'm currently developing my first application with Rails and Hotwire. It includes a comment form visible to all users. When unauthenticated users submit it, I'd like to open the login form (managed by Devise) in a modal on top of the form.

Currently I came up with the following solution, but it seems quite hacky and I'm wondering if anyone had thought of a cleaner solution to this probably very common use case?

  1. I have a <turbo-frame id="modal> in my layout and my login form
  2. In the _form.html.erb partial, I check if the user is logged in and if not, I add a data-turbo-frame="modal" attribute to the form.
  3. In my create action, I check if the user is logged in and if not, I redirect him to the new_user_session_path

Again, this is doing the job but I don't like the fact that it requires changes in both the views and the controller, which makes it difficult to scale (in case I want to apply the same flow to other forms).

Thank you very much!

1

There are 1 best solutions below

0
On

You could do a turbo-stream render in a before action in the controller.

class ApplicationController
 def render_auth_modal
   render turbo_stream: turbo_stream.update("modal",
   partial: "auth/modal")
 end
end

class CommentsController < ApplicationController
  before_action :render_auth_modal, unless: :signed_in?
end