From 1b2de86007508ba86c6c9cb99fbdcac178045131 Mon Sep 17 00:00:00 2001 From: David Gay Date: Sun, 2 May 2021 22:38:32 -0400 Subject: Character items and inventory, with ability to add and remove items --- app/models/character.rb | 10 ++++++++++ app/models/character_item.rb | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 app/models/character_item.rb (limited to 'app/models') diff --git a/app/models/character.rb b/app/models/character.rb index 1c022ea..a158d88 100644 --- a/app/models/character.rb +++ b/app/models/character.rb @@ -1,5 +1,15 @@ class Character < ApplicationRecord belongs_to :user belongs_to :activity, optional: true + has_many :character_items + has_many :items, through: :character_items validates :name, presence: true + + def shift_item(gid, amount) + CharacterItem.transaction do + item = self.character_items.find_or_initialize_by(item: Item.find_by_gid(gid)) + item.increment(:quantity, amount) + item.save + end + end end diff --git a/app/models/character_item.rb b/app/models/character_item.rb new file mode 100644 index 0000000..b54f799 --- /dev/null +++ b/app/models/character_item.rb @@ -0,0 +1,25 @@ +class CharacterItem < ApplicationRecord + belongs_to :character + belongs_to :item + validates :quantity, presence: true + + after_initialize do + if self.new_record? + self.quantity ||= 0 + end + end + + after_save :destroy_if_zero_quantity + + scope :ordered_by_item_name, -> { includes(:item).order("items.name") } + + private + def destroy_if_zero_quantity + if self.quantity == 0 + destroy + elsif self.quantity < 0 + # TODO: Can improve this (at the least, with reporting, later). + raise ItemQuantityError + end + end +end -- cgit v1.2.3