Class: Invitation::InvitesController

Inherits:
ApplicationController
  • Object
show all
Defined in:
app/controllers/invitation/invites_controller.rb

Overview

Invitation::InvitesController - issue invitations to users via email address.

Controller uses an (inner class) Form object that is not a persisted model. The form can accept many email addresses, and creates on Invite per email address.

Subclass and modify or extend, or copy the controller into your app with `rails generate invitation:controller`.

Common extensions include:

  • add authorization checks: subclass and add before_actions to :new and :create.

  • override after_invite_existing_user or after_invite_new_user

Defined Under Namespace

Classes: InviteForm

Instance Method Summary collapse

Instance Method Details

#createObject

Create one or more Invite instances.

invite: { invitable_id, invitable_type, email or emails:[] }

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/controllers/invitation/invites_controller.rb', line 22

def create
  failures = []
  invites = InviteForm.new(invite_params).build_invites(current_user)
  ActiveRecord::Base.transaction do
    invites.each { |invite| invite.save ? do_invite(invite) : failures << invite.email }
  end
  logger.info "!!!!!!!!!!!!!!!!!!!!! INSIDE CREATE: current_user: #{current_user.inspect}"
  respond_to do |format|
    format.html do
      if failures.empty?
        flash[:notice] = t('invitation.flash.invite_issued', count: invites.count)
      else
        flash[:error] = t('invitation.flash.invite_error', count: failures.count, email: failures.to_sentence)
      end
      redirect_to url_after_invite(invites.first) # FIXME: redirect to back
    end
    format.json do
      if failures.empty?        # If we received a single email, json response should be a scalar, not an array.

        invites = params[:invite].key?('email') ? invites.first : invites
        render json: invites.as_json(except: [:token, :created_at, :updated_at]), status: 201
      else
        render json: {
          message: t('invitation.flash.invite_error', count: failures.count, email: failures.to_sentence),
          status: :unprocessable_entity
        }
      end
    end
  end
end

#newObject


14
15
16
17
# File 'app/controllers/invitation/invites_controller.rb', line 14

def new
  @invite = InviteForm.new(invite_params)
  render template: 'invites/new'
end