aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/clients_controller.rb
blob: a8087c7ac0e3809b148575978d15c2b089c80a13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class ClientsController < ApplicationController

  def new
    @client = Client.new
  end

  def create
    @client = Client.new(client_params)

    if @client.save
      redirect_to root_path, notice: 'Client Created!'
    else
      render :new, status: :unprocessable_entity
    end
  end

  def show
    @client = Client.includes(:household_members).find_by(uuid: params[:uuid])

    if @client.nil?
      redirect_back fallback_location: root_path, alert: 'Client not found!'
    end
  end

  def edit
    @client = Client.find(params[:id])
  end

  def update
    @client = Client.find(params[:id])
    if @client.update(client_params)
      redirect_to show_clients_path(uuid: @client.uuid), notice: 'Client Updated!'
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def find
    query = params[:q].downcase
    json = Client.where('lower(first_name) LIKE ? OR lower(last_name) LIKE ? OR mobile_number = ?', query, query, query)
      .select(:uuid, :first_name, :last_name, :mobile_number)
      .as_json

    render json: json
  end

  private

  def client_params
    params.require(:client).permit(
      :first_name,
      :last_name,
      :mobile_number,
      :address,
      :notes,
      household_members_attributes: [
        :first_name,
        :last_name,
        :member_type,
        :id,
        :_destroy,
      ],
    )
  end
end