summaryrefslogtreecommitdiff
path: root/app/controllers/beds_controller.rb
blob: c213978619a0116c6455e527f347b2d3563ee480 (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
class BedsController < ApplicationController
  before_action :set_bed, only: %i[ edit update ]
  before_action :get_crops, only: %i[ index edit update ]

  def index
    @beds = Bed.all
  end

  def edit
  end

  def update
    if @bed.update(bed_params)
      redirect_to beds_path, notice: "Bed #{@bed.id} successfully updated."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def bulk_assign_crops
    crop = Crop.find(params[:crop_id])
    Raft.update_all(crop_id: crop.id)
    redirect_back fallback_location: root_path, notice: "All rafts set to #{crop.name}."
  end


  def reset_seed_crops
    # mirrors seed logic
    tomatoes = Crop.find_by!(name: :tomatoes)
    chives   = Crop.find_by!(name: :chives)
    lettuce  = Crop.find_by!(name: :lettuce)

    Bed.includes(:rafts).find_each do |bed|
      default_crop =
        case bed.location
        when 1..3 then tomatoes
        when 4..7 then chives
        else            lettuce
        end
      bed.rafts.update_all(crop_id: default_crop.id)
    end
    redirect_back fallback_location: root_path, notice: "Raft crops reset to default seed layout."
  end

  private

  def set_bed
    @bed = Bed.find(params[:id])
  end

  def get_crops
    @crops = Crop.order(:name)
  end

  def bed_params
    params.require(:bed).permit(
      :location,
      rafts_attributes: %i[id crop_id]
    )
  end
end
Copyright 2019--2025 Marius PETER