Skip to content

Conditional invitation

Bruno Freitas edited this page Aug 27, 2014 · 1 revision

Sometimes it might be unnecessary to send the invitation email.

Consider a situation where the invitation form (view) includes an optional password field. If the password is informed, the user can be automatically added (with the given password), while if the password is left blank, the invitation email should be sent.

To accomplish this, it would be necessary to overwrite the method create, and also define the method invite_resource_and_skip, as follows:

# POST /resource/invitation
def create
  if params["password"].present?
    self.resource = invite_resource_and_skip
    self.resource.assign_attributes(:password => params["password"], :password_confirmation => params["password"])
    self.resource.accept_invitation!
  else
    self.resource = invite_resource
  end

  if resource.errors.empty?
    yield resource if block_given?

    if params["password"].present?
      set_flash_message :notice, :user_added, :email => self.resource.email
    else
      set_flash_message :notice, :send_instructions, :email => self.resource.email
    end

    respond_with resource, :location => after_invite_path_for(resource)
  else
    respond_with_navigational(resource) { render :new }
  end
end

protected

def invite_resource_and_skip
  resource_class.invite!(invite_params, current_inviter) do |u|
    ## skip sending emails on invite
    u.skip_invitation = true
  end
end

It would also be necessary to add the key user_added on the I18n file:

en:
  devise:
    invitations:
      user_added: 'The user %{email} has been correctly added.'
      ...