'Login flow with Hotwire
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?
- I have a
<turbo-frame id="modal>in my layout and my login form - In the
_form.html.erbpartial, I check if the user is logged in and if not, I add adata-turbo-frame="modal"attribute to the form. - In my
createaction, I check if the user is logged in and if not, I redirect him to thenew_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!
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yungindigo |
