I tried to summarize again the devise that was difficult at first sight

Introduction

Continuation of the previous "I tried to summarize devise that was difficult at first sight". This time about the logout function. Click here for the previous post explaining the introduction of devise ↓ https://qiita.com/TerToEer_sho/items/b5523ad100d08126a547

Implementation of logout function

In the first place, the logout button is only needed by the logged-in user. In other words If you are logged in, display the logout button. </ font> Also, if you are logged in, you do not need the logout button. In other words If you are not logged in, display the login button. </ font>

So how do you know if you're logged in? This is another great thing about devise, and there are methods that you can use by installing devise's Gem.

user_signed_in? method </ font>

As translated into Japanese, it returns whether or not you are signed in as a boolean value (true / false).

You are logged in → true Not logged in → false

I don't know the details of why I can tell if I'm logged in.

By using the fact that the boolean value is returned by the user_signed_in? method, conditional branching is performed using the if statement.

In other words

Ruby:index.html.erb


<% if user_signed_in? %>
 <%= link_to 'Log out', destroy_user_session_path, method: :delete %>
<% else %>
 <%= link_to 'Login', new_user_session_path %>
 <%= link_to 'sign up', new_user_registration_path %>
<% end %>

If you write the code using the Rails view file as an example, it will look like this.

The point to be careful is

① In logout, set the HTTP method to "delete" in the third argument of the link_to method. </ font> As an image, it feels like deleting the logged-in state. By the way, if you do not set it to "delete", an error will occur. The reason is that the default HPPT method of the link_to method is "get". As you read link_to, it's a method that says "I'll skip to the link destination".

② Regarding the path of the second argument At the terminal

rails routes

And confirm. Unless otherwise specified, the same as above is fine.

point

-[x] Use the user_signed_in? method to determine the login status. -[x] It is possible to branch the display using an if statement. -[x] When describing logout with link_to method, "method:: delete" is required as the third argument.

Finally

It can be implemented with less work because the convenient user_signed_in method can be used.

Recommended Posts