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

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

11
  def show; end
12
13
14

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

20
  def edit; end
21
22
23

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

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

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

  private

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

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

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