Logging Out and Registering On the Fly

Subscribe for full access to every course, or buy this one on its own.
Rails is helpful when it comes to providing a positive experience for your user, and one of those helpful things is to not make any changes with a simple GET request, such as logging someone out. To that end, we need to figure out how we can comply with this notion without writing a bunch of code! Thankfully, it's straightforward:
<span class="language-xml"><%=</span><span class="language-ruby"> button_to <span class="hljs-string">"Logout"</span>, destroy_user_session_path, <span class="hljs-symbol">method:</span> <span class="hljs-symbol">:delete</span>, <span class="hljs-symbol">data:</span> {<span class="hljs-symbol">turbo:</span> <span class="hljs-literal">false</span>} </span><span class="language-xml">%></span>
OK, maybe that's not entirely straightforward! We have to use button_to because the link_to helper will only create an anchor tag, which fires a GET request. The button_to helper will create a form for us with the correct method. By adding data: {turbo: false}, we're also turning off turbo links, which can mess with the form submission.
The next task is overriding the base controller with our own (controllers/users/passwordless_controller.rb):
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Users::PasswordlessController</span> < <span class="hljs-title class_ inherited__">Devise::Passwordless::SessionsController</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">create</span>
<span class="hljs-keyword">if</span> params[<span class="hljs-symbol">:user</span>].<span class="hljs-literal">nil</span>? |<span class="hljs-params"></span>| params[<span class="hljs-symbol">:user</span>][<span class="hljs-symbol">:email</span>].<span class="hljs-literal">nil</span>?
<span class="hljs-keyword">return</span> redirect_to new_user_session_path, <span class="hljs-symbol">alert:</span> <span class="hljs-string">"Please enter an email address"</span>
<span class="hljs-keyword">end</span>
user = <span class="hljs-title class_">User</span>.find_by(<span class="hljs-symbol">email:</span> params[<span class="hljs-symbol">:user</span>][<span class="hljs-symbol">:email</span>])
<span class="hljs-keyword">unless</span> user
user = <span class="hljs-title class_">User</span>.create(<span class="hljs-symbol">email:</span> params[<span class="hljs-symbol">:user</span>][<span class="hljs-symbol">:email</span>])
<span class="hljs-keyword">end</span>
user.send_magic_link
redirect_to new_user_session_path, <span class="hljs-symbol">notice:</span> <span class="hljs-string">"Magic link sent!"</span>
<span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
Subscribe for full access to every course, or buy this one on its own.