Edward
Edward

Reputation: 967

Log in user after accept invitation using rails with devise_invitable

I use devise_invitable with Rails and need some help. I want make user logged in after accept invitation. Here is my InvitationsController

class InvitationsController < Devise::InvitationsController
  def update
    if User.accept_invitation!(user_params)
      # log in user here
      redirect_to dashboard_show_path, notice: t('invitaion.accepted')
    else
      redirect_to root_path, error: t('invitation.not_accepted')
    end
  end

  private
  def user_params
    params.require(:user).permit(:invitation_token, :password, :password_confirmation)
  end
end

You can see comment in code

# log in user here

here I want log in the user who has accept the invitation.

Thanks.

Upvotes: 0

Views: 2262

Answers (2)

Anton S.
Anton S.

Reputation: 1029

Here is a minor update for the Noz version:


# invitations_controller.rb

def update
  user = User.accept_invitation!(update_resource_params)

  if user
    sign_in(user)
    redirect_to root_path, notice: t('devise.layout.edit_invitation.accepted')
  else
    redirect_to root_path
  end
end

private

def update_resource_params
  params.require(:user).permit(:password, :first_name, :last_name, :invitation_token)
end

This definition update won't throw Could not find a valid mapping for {...} and instead login the user after invitation acceptance.

Upvotes: 0

Noz
Noz

Reputation: 6346

The method your looking for is sign_in, try this:

def update
  if User.accept_invitation!(user_params)
    sign_in(params[:user])
    redirect_to dashboard_show_path, notice: t('invitaion.accepted')
  else
    redirect_to root_path, error: t('invitation.not_accepted')
  end
end

However I should note that devise_invitable, by default, signs in users after they have accepted an invitation. See the default update action here, if you wish to use the default functionality simply call the super method or don't implement the update action at all.

Upvotes: 1

Related Questions