volunteers_controller.rb 1.69 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
25
    @volunteer.schedules << Schedule.build
    @volunteer.build_contact
26
    @volunteer.registrar = current_user
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
36
37
    state_was_registered = @volunteer.registered?
    return render :edit unless @volunteer.update(volunteer_params)
38
    if state_was_registered && @volunteer.accepted? && invite_volunteer_user
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