volunteers_controller.rb 1.53 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
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
16
    authorize @volunteer
17
18
  end

19
  def edit; end
20
21
22

  def create
    @volunteer = Volunteer.new(volunteer_params)
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
23
    authorize @volunteer
24
25
26
27
    if @volunteer.save
      redirect_to @volunteer, notice: t('volunteer_created')
    else
      render :new
28
29
30
31
    end
  end

  def update
32
33
34
35
    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')
36
37
38
39
  end

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

  private

45
46
47
48
49
  def invite_volunteer_user
    new_user = User.new(email: @volunteer.email, password: Devise.friendly_token, role: 'volunteer')
    new_user.save
    new_user.invite!
    redirect_to volunteers_path, notice: t('invite_sent', email: new_user.email)
50
51
  end

52
53
  def set_volunteer
    @volunteer = Volunteer.find(params[:id])
54
    authorize @volunteer
55
56
57
  end

  def volunteer_params
58
    params.require(:volunteer).permit(
59
60
      volunteer_attributes,
      language_skills_attributes, relatives_attributes, schedules_attributes
61
    )
62
63
  end
end