Add exit button to RESTFUL authentication

I installed RESTFUL authentication and everything works fine. I can register and login. the only way I can exit is to enter the URL http: // localhost: 3000 / logout

How to add the exit button to the page? I tried adding it to .rhtml members

<%= link_to "logout", :controller=> "sessions", :action=> "destroy" %> 

which refers to session_controller.rb but I get the error message "No action responds to the display. Actions: create, destroy and new"

any thoughts? thanks

+8
ruby-on-rails restful-authentication logout
source share
2 answers

What do you have in the routes file?

Try to put

 map.log_out 'logout', :controller => 'sessions', :action => 'destroy' 

in your routes.

Then just

 <%= link_to "Sign out", log_out_url %> 

for the dropdown link.

EDIT

It all depends on how you specify routing.

Since you had map.log_out in routing, then the URL http: // localhost: 3000 / logout is picked up by this and headed for the correct action.

If you have:

 <%= link_to "logout", :controller=> "sessions", :action=> "destroy" %> 

This will create a link for http: // localhost: 3000 / session . But he does nothing for routing. You still need to specify the correct routes.

Note that Rails does not add the destroy action to the URL. (It will not create http: // localhost: 3000 / session / destroy .) It is assumed that if you have an destroy action, you will send it using DELETE http verb, for some reason it is not completely perfect, and on in fact, it does not by default send the verb DELETE.

You can make it do this:

 <%= link_to "logout", {:controller=> "user_sessions", :action=> "destroy"}, :method => :delete%> 

It still won’t work unless you type it correctly. If you put the following in routes:

 map.resource :session 

Then the rails will generate routing for all verbs and indicate default actions for them, including DELETE. More information can be found here: Rails Routing from Outside In .

This whole page is worth reading over and over until you understand it. Routing is the key to understanding Rails!

For a simple controller such as sessions, it’s easier to just specify the log_out route and then a link to log_out_url ..

(Hope that makes sense, sleep deprivation is creeping!)

+8
source share

If you use devise and your interested model is User , the elegant way is here:

 <%= link_to 'logout', destroy_user_session_path, method: :delete %> 

This works because:

  • Due to the HTTP methods GET, POST, PUT, PATCH and DELETE, so method: :delete (not method: :destroy )
  • we use destroy_user_session_path with the will and user model, as usual, if you define a different model name, such as the manager you just change the exit path from the system destroy_manager_session_path
+1
source share

All Articles