volunteers_controller.rb 1.76 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
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(
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
67
68
      volunteer_attributes, language_skills_attributes, schedules_attributes,
      contact_attributes
69
    )
70
71
  end
end