Rails - How to override devise SessionsController to perform specific tasks when user signs in?

后端 未结 3 1236
囚心锁ツ
囚心锁ツ 2020-12-02 22:39

Using Devise to manage users sessions / registrations I would need to perform specific tasks (updating some fields in the users table for this specific user for example) eac

3条回答
  •  天涯浪人
    2020-12-02 23:13

    If you look at Devise's implementation of sessions_controller#create, you'll notice that they yield if you pass a block.

    So, just subclass their sessions controllers and pass a block when you call super. To do that, first tell Devise in routes.rb that you'd like to use your own sessions controller:

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

    And then create a SessionsController class and pass a block when you call super in your create method. It would look something like this:

    class Users::SessionsController < Devise::SessionsController
      layout "application"
    
      # POST /login
      def create
        super do |user|
          if user.persisted?
            user.update(foo: :bar)
          end
        end
      end
    end
    

    Most of the Devise controller methods accept a block, so you could do this for registration, forgot password, etc as well.

提交回复
热议问题