volunteers_controller.rb 1.65 KB
Newer Older
1
class VolunteersController < ApplicationController
2
  include NestedAttributes
3
  include ContactAttributes
4
  include VolunteerAttributes
5
6
7
  before_action :set_volunteer, only: [:show, :edit, :update, :destroy]

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

12
  def show; end
13
14
15

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

21
  def edit; end
22
23
24

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

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

  def destroy
    @volunteer.destroy
47
    redirect_to volunteers_url, notice: t('volunteer_destroyed')
48
49
50
51
  end

  private

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

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

  def volunteer_params
66
    params.require(:volunteer).permit(volunteer_attributes)
67
68
  end
end