From 4ec1c1ce2695e5a74d870c6b6e8081db454573c8 Mon Sep 17 00:00:00 2001 From: Karim Bogtob Date: Sun, 26 Mar 2023 16:09:27 +0200 Subject: [PATCH] 2.6B - Setter la size a la creation --- README.md | 23 ++++++++++++++++++++++- app/models/creature.rb | 11 ++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 49f7d25..fc9b6b6 100644 --- a/README.md +++ b/README.md @@ -70,4 +70,25 @@ Question 2.6 : * Je génère la migration avec `rails g migration AddSizeColumnToCreatures size:integer` -* `rails db:migrate` \ No newline at end of file +* `rails db:migrate` + +* J'ajoute le callback comme dans le sujet du TP pour setter la size à la création, je teste en console : + +```ruby +irb(main):001:0> Creature.create(name: 'Big Chongus', health_points: 25) + TRANSACTION (0.1ms) begin transaction + Creature Create (0.4ms) INSERT INTO "creatures" ("name", "health_points", "created_at", "updated_at", "size") VALUES (?, ?, ?, ?, ?) [["name", "Big Chongus"], ["health_points", 35], ["created_at", "2023-03-26 14:07:03.876318"], ["updated_at", "2023-03-26 14:07:03.876318"], ["size", 2]] + TRANSACTION (0.6ms) commit transaction +=> +# +``` + +Toutes les créatures crées auront dorénavant une taille. + + diff --git a/app/models/creature.rb b/app/models/creature.rb index 7cc33c5..272d106 100644 --- a/app/models/creature.rb +++ b/app/models/creature.rb @@ -7,5 +7,14 @@ class Creature < ApplicationRecord "#{name} (#{health_points})" end - + before_create do + self.size = case health_points + when 0..10 + :small + when 11..30 + :big + else + :giant + end + end end