volunteers_controller.rb 1.56 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
8
9
10
11
12
13

  def index
    @volunteers = Volunteer.all
  end

  def show; end

  def new
    @volunteer = Volunteer.new
14
    @volunteer.schedules << Schedule.build
15
16
17
18
19
20
  end

  def edit; end

  def create
    @volunteer = Volunteer.new(volunteer_params)
21
22
23
24
    if @volunteer.save
      redirect_to @volunteer, notice: t('volunteer_created')
    else
      render :new
25
26
27
28
    end
  end

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

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

  private

51
52
53
54
  def set_state
    @state = @volunteer.state
  end

55
56
57
58
59
  def set_volunteer
    @volunteer = Volunteer.find(params[:id])
  end

  def volunteer_params
60
    params.require(:volunteer).permit(
61
          volunteer_attributes,
62
63
64
          language_skills_attributes: language_skills_attributes,
          relatives_attributes: relatives_attributes,
          schedules_attributes: schedules_attributes)
65
66
  end
end