volunteers_controller.rb 1.62 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

  def index
7
    @q = Volunteer.ransack(params[:q] || { state_cont: 'registered' })
8
    @volunteers = @q.result
9
10
  end

11
  def show; end
12
13
14

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

19
  def edit; end
20
21
22

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

  def update
32
    if @volunteer.update(volunteer_params)
33
      if @state == Volunteer::INTERESTED && @volunteer.state == Volunteer::ACCEPTED
34
35
        new_user = User.new(email: @volunteer.email,
          password: Devise.friendly_token, role: 'volunteer')
36
        new_user.save
37
38
39
40
41
        new_user.invite!
        redirect_to volunteers_path, notice: t('invite_sent', email: new_user.email)
      else
        redirect_to @volunteer, notice: t('volunteer_updated')
      end
42
43
    else
      render :edit
44
45
46
47
48
    end
  end

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

  private

54
55
56
57
  def set_state
    @state = @volunteer.state
  end

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

63
64


65
  def volunteer_params
66
    params.require(:volunteer).permit(
67
68
69
70
      volunteer_attributes.push(
        language_skills_attributes, relatives_attributes, schedules_attributes
      )
    )
71
72
  end
end