1

I'm using Devise and Piggybak for a Rails project and Piggybak uses a cookie named cart to store the user cart. The problem is that Piggybak doesn't destroy the cookie on user sign_out so, if I sign_in with another user, it uses the same cookie and therefore, the same cart.

I want to solve that storing that cookie value into my user model, enabling it to get back his cart on another sign_in. What I did was overriding the Devise.sessions#destroy method to save the cookie value on user and destroy the cookie:

# app/controllers/users/sessions_controller.rb

class Users::SessionsController < Devise::SessionsController

  def destroy
    current_user.add_cart_cookie(cookies['cart']['value'])
    cookies['cart'] = { value: '', path: '/' }
    super
  end
end

Routing it right in the routes:

# config/routes.rb

...

devise_for :users, controllers: { sessions: 'users/sessions' }

...

And creating the method add_cart_cookie to my user model:

# app/models/user.rb

class User < ActiveRecord::Base

...

  def add_cart_cookie(value)
    self.cart_cookie = value
  end

...

end

But this is not working, it destroy the cookie but don't save it on the user model. Why is this happening?

1 Answers1

0

Did it, thank you @Marian.

What I did was change my add_cookie_cart method to accept another parameter:

# app/models/user.rb

class User < ActiveRecord::Base

...

  def add_cart_cookie(value, password)
    self.cart_cookie = value
    self.password = password
    self.password_confirmation = password
    self.save
  end

...

end

And changed my session#destroy accordingly:

class Users::SessionsController < Devise::SessionsController

  def destroy
    current_user.add_cart_cookie(cookies['cart']['value'], current_user.password)
    cookies['cart'] = { value: '', path: '/' }
    super
  end
end