Muktadir
Muktadir

Reputation: 303

Signout from a controller in rails 4

I want to signout from a controller. My controller looks like

def update
if @attendance.update_attribute(:logout_at, Time.now.localtime)
  redirect_to signout_path and return
end
end

And my routes looks like

  devise_scope :employees do
     get "signout" => "devise/sessions#destroy"

  end

  devise_for :employees, :controllers => { registrations: 'registrations' }

But It gives error

Unknown action

Could not find devise mapping for path "/signout". This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user]

How can I do that? Please Help me out.

Thanks in advance.

Upvotes: 2

Views: 1572

Answers (1)

Mohamad
Mohamad

Reputation: 35359

You are redirecting, which makes a GET request to devise#sessions#destroy, a route that doesn't exist. The signout route in Devise is a mapped to a DELETE request. Instead of redirecting you should directly call the sign_out method that Devise makes available to you. After that be sure to redirect the user somewhere, maybe the login page.

A side note, in Rails 4 you can call update(attribute: value) directly. You don't need to call return either.

def update
  @attendance.update(logout_at: Time.now.localtime)
  sign_out
  redirect_to login_path      
end

I removed the if statement that wrapped the update call. By using one you are implying that there maybe a reason the save will not happen because of validation error, for example, and you need to provide feedback to the user. But in this case it's more likely to be an exception since there is no data input by the user. You can handle that at the application level.

Upvotes: 4

Related Questions