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

  def index
    @volunteers = Volunteer.all
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
8
    authorize Volunteer
9
10
  end

Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
11
12
13
  def show
    authorize @volunteer
  end
14
15
16

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

Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
21
22
23
  def edit
    authorize @volunteer
  end
24
25
26

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

  def update
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
36
    authorize @volunteer
37
    if @volunteer.update(volunteer_params)
38
      if @state == Volunteer::INTERESTED && @volunteer.state == Volunteer::ACCEPTED
39
40
        new_user = User.new(email: @volunteer.email,
          password: Devise.friendly_token, role: 'volunteer')
41
        new_user.save
42
43
44
45
46
        new_user.invite!
        redirect_to volunteers_path, notice: t('invite_sent', email: new_user.email)
      else
        redirect_to @volunteer, notice: t('volunteer_updated')
      end
47
48
    else
      render :edit
49
50
51
52
    end
  end

  def destroy
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
53
    authorize @volunteer
54
    @volunteer.destroy
55
    redirect_to volunteers_url, notice: t('volunteer_destroyed')
56
57
58
59
  end

  private

60
61
62
63
  def set_state
    @state = @volunteer.state
  end

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

  def volunteer_params
69
    params.require(:volunteer).permit(
70
          volunteer_attributes,
71
72
73
          language_skills_attributes: language_skills_attributes,
          relatives_attributes: relatives_attributes,
          schedules_attributes: schedules_attributes)
74
75
  end
end