volunteers_controller.rb 1.67 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)
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
36
37
    state_was_registered = @volunteer.registered?
    return render :edit unless @volunteer.update(volunteer_params)
    return invite_volunteer_user if state_was_registered && @volunteer.accepted?
    redirect_to @volunteer, notice: t('volunteer_updated')
38
39
40
41
  end

  def destroy
    @volunteer.destroy
42
    redirect_to volunteers_url, notice: t('volunteer_destroyed')
43
44
45
46
  end

  private

47
  def invite_volunteer_user
48
49
    new_user = User.new(email: @volunteer.contact.contact_emails.first.body,
      password: Devise.friendly_token, role: 'volunteer')
50
    new_user.save
51
    @volunteer.user = new_user
52
53
    new_user.invite!
    redirect_to volunteers_path, notice: t('invite_sent', email: new_user.email)
54
55
  end

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

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