From f5bdb92a2a0fa38162decc5a7d0fe96caa5a2dcb Mon Sep 17 00:00:00 2001 From: Karim Bogtob Date: Sun, 26 Mar 2023 16:03:16 +0200 Subject: [PATCH] 2.5 - Scope alive --- README.md | 26 +++++++++++++++++++++++++ app/controllers/creatures_controller.rb | 2 +- app/models/creature.rb | 2 ++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 44bb326..cae424c 100644 --- a/README.md +++ b/README.md @@ -40,3 +40,29 @@ Question 3.2 : * `rails db:seed` +## TP4 + +Question 2.5 : + +* J'ajoute une créature avec des PVs à 0 : + +```ruby +❯ rails console +Loading development environment (Rails 7.0.4.3) +irb(main):001:0> Creature.create(name: 'Zombie', health_points: 0) + TRANSACTION (0.1ms) begin transaction + Creature Create (0.4ms) INSERT INTO "creatures" ("name", "health_points", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "Zombie"], ["health_points", 0], ["created_at", "2023-03-26 14:00:56.413028"], ["updated_at", "2023-03-26 14:00:56.413028"]] + TRANSACTION (0.9ms) commit transaction +=> +# +``` + +* J'essaie de renommer la créature dans postman et je vérifie que son nom ne change pas + +* J'ai bien une 404 et son nom n'a pas changé + diff --git a/app/controllers/creatures_controller.rb b/app/controllers/creatures_controller.rb index ad02c6b..d776b71 100644 --- a/app/controllers/creatures_controller.rb +++ b/app/controllers/creatures_controller.rb @@ -21,7 +21,7 @@ class CreaturesController < ApplicationController end def update - @creature = Creature.find(params[:id]) + @creature = Creature.alive.find(params[:id]) @creature.update!(create_or_update_params) render json: @creature.as_json(only: SHOWABLE_ATTRIBUTES) rescue ActiveRecord::RecordNotFound diff --git a/app/models/creature.rb b/app/models/creature.rb index 3f60ae6..129c7c1 100644 --- a/app/models/creature.rb +++ b/app/models/creature.rb @@ -1,4 +1,6 @@ class Creature < ApplicationRecord + scope :alive, -> { where('health_points > 0') } + def to_label "#{name} (#{health_points})" end