volunteers_controller.rb 1.62 KB
Newer Older
1
class VolunteersController < ApplicationController
2
  include NestedAttributes
3
  include ContactAttributes
4
  include VolunteerAttributes
5
6
  include MakeNotice

7
8
9
  before_action :set_volunteer, only: [:show, :edit, :update, :destroy]

  def index
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
10
    @q = Volunteer.ransack(params[:q])
11
    @volunteers = @q.result
12
13
  end

14
  def show; end
15
16
17

  def new
    @volunteer = Volunteer.new
18
    @volunteer.schedules << Schedule.build
19
    @volunteer.build_contact
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
20
    authorize @volunteer
21
22
  end

23
  def edit; end
24
25
26

  def create
    @volunteer = Volunteer.new(volunteer_params)
27
    @volunteer.registrar = current_user
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
28
    authorize @volunteer
29
    if @volunteer.save
30
      redirect_to @volunteer, make_notice
31
32
    else
      render :new
33
34
35
36
    end
  end

  def update
37
38
    state_was_registered = @volunteer.registered?
    return render :edit unless @volunteer.update(volunteer_params)
39
    if state_was_registered && @volunteer.accepted? && invite_volunteer_user
40
41
      redirect_to volunteers_path,
        notice: t('invite_sent', email: @volunteer.contact.contact_emails.first.body)
42
    else
43
      redirect_to @volunteer, make_notice
44
    end
45
46
47
48
  end

  def destroy
    @volunteer.destroy
49
    redirect_to volunteers_url, make_notice
50
51
52
53
  end

  private

54
  def invite_volunteer_user
55
    new_user = User.new(
56
      email: @volunteer.contact.contact_emails.first.body, password: Devise.friendly_token,
57
58
      role: 'volunteer', volunteer: @volunteer
    )
59
    new_user.save && new_user.invite!
60
61
  end

62
63
  def set_volunteer
    @volunteer = Volunteer.find(params[:id])
64
    authorize @volunteer
65
66
67
  end

  def volunteer_params
68
    params.require(:volunteer).permit(volunteer_attributes)
69
70
  end
end