aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/searches_controller.rb
blob: 376455cfb561d902c6f80f79a5c77b519631b347 (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
# frozen_string_literal: true

class SearchesController < ApplicationController
  before_action :set_search, only: %i[show edit update destroy]

  def index
    current_user.update!(last_search_id: nil)
    @search = Search.new
  end

  def show
    current_user.update!(last_search_id: @search.id)
  end

  def new
    @search = Search.new
  end

  def edit; end

  def create
    @search = Search.new(search_params)
    @search.user_id = @current_user.id

    if @search.save
      redirect_to @search
    else
      render :new, status: :unprocessable_entity
    end
  end

  def update
    if @search.update(search_params)
      redirect_to @search, status: :see_other
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @search.destroy!
    redirect_to searches_url, status: :see_other
  end

  def search
    @search = Search.new
    @search.body = params.permit(:body).fetch(:body, '')
    render 'search', partial: true, locals: { items: @search.results }
  end

  protected

  def set_search
    @search = Search.find(params[:id])
  end

  def search_params
    params.require(:search).permit(:name, :body, :description, :shared)
  end
end