volunteers_controller.rb 1.8 KB
Newer Older
1
class VolunteersController < ApplicationController
2
  include NestedAttributes
3
  include VolunteerAttributes
Tugce Nur Tas's avatar
Tugce Nur Tas committed
4
  include ContactAttributes
5
6
7
  before_action :set_volunteer, only: [:show, :edit, :update, :destroy]

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

12
  def show; end
13
14
15

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

21
  def edit; end
22
23
24

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

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

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

  private

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

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

  def volunteer_params
67
    params.require(:volunteer).permit(
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
68
69
      volunteer_attributes, language_skills_attributes, schedules_attributes,
      contact_attributes
70
    )
71
72
  end
end