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

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

  private

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

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

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