Class: LightSwitch::SwitchesController

Inherits:
ApplicationController show all
Defined in:
app/controllers/light_switch/switches_controller.rb

Instance Method Summary collapse

Instance Method Details

#createObject



9
10
11
12
13
14
15
16
17
18
19
20
# File 'app/controllers/light_switch/switches_controller.rb', line 9

def create
  @switch = Switch.new(switch_params.slice(:name))

  if @switch.save
    redirect_to [:switches], notice: "Switch #{@switch.name} was successfully created.", status: :see_other
  else
    render :index, status: :unprocessable_entity
  end
rescue ActiveRecord::RecordNotUnique
  @switch.errors.add(:name, "already taken")
  render :index, status: :unprocessable_entity
end

#destroyObject



36
37
38
39
40
# File 'app/controllers/light_switch/switches_controller.rb', line 36

def destroy
  switch = Switch.find_by(id: params[:id])
  switch&.destroy!
  redirect_to [:switches], notice: "Switch #{switch.name} was successfully deleted.", status: :see_other
end

#indexObject



5
6
7
# File 'app/controllers/light_switch/switches_controller.rb', line 5

def index
  @switch = Switch.new
end

#updateObject



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/controllers/light_switch/switches_controller.rb', line 22

def update
  @switch = Switch.find(params[:id])

  if @switch.update(switch_params.slice(:state))
    redirect_to [:switches], notice: "Switch #{@switch.name} was successfully updated.", status: :see_other
  else
    errors = @switch.errors.full_messages.to_sentence
    @switch.restore_attributes
    redirect_to [:switches], alert: "Failed to update Switch #{@switch.name}: #{errors}", status: :see_other
  end
rescue ActiveRecord::RecordNotFound
  redirect_to [:switches], alert: "Failed to update Switch because it has been deleted.", status: :see_other
end