Ruby on Rails doubts

Asked

Viewed 90 times

1

I have this def no models, I checked with Pry and have values coming normally, however they do not save on the variable @Inventory and below I put the class Inventory also, I wonder if someone could give a help, since I thank you.

MODEL TRADE

        def survivor_owns_items(survivor, trade_items)
        trade_items.each do |trade_item|
            binding.pry 
            @inventory = Inventory.includes(:Survivor,:Item).where({Survivor: survivor, Item: trade_items})
            if @inventory.quantity < trade_items.quantity
                return false
            end
        end

INVENTORY CLASS

           class Inventory < ApplicationRecord
             belongs_to :survivor
             belongs_to :item
            validates :survivor, :item, presence: true
            validates :survivor, uniqueness: { scope: :item }
          end

JSON:

     {
     "trade": {
        "survivor_one_id": "1",        
         "survivor_two_id": "2",
         "survivor_two_items": [{"name": "Water", "quantity":"1"}],                       
         "survivor_one_items": [{"name":"Medication","quantity":"2"}]
        }
     }
  • shouldn’t be @inventory = Inventory.includes(:Survivor,:Item).where({Survivor: survivor, Item: trade_item}), without’s'?

  • while @inventory.quantity < trade_items.quantity for false, he overwrites @inventory, that is the intention?

  • The purpose of the comparison is to check if I have sufficient amount of the item that I will in the future make a trade with another player, if it does not return false only,I made the proposed change, that was surely a mistake, however the main one has not been corrected, when run checked with Pry what I have in @Inventory it returns: Inventory => []

  • for each trade_item in trade_items, the code after binding_pry returns a array? (I’m trying to understand the reason for comparison within iteration)

  • Yes, I forgot to mention that it’s Rest api, so the following JSON is passed(added up there), yes there may be more items so I go through my items comparing them.

  • good - better edit and include this information in your question; I also suggest that you separate it into blocks of code so it doesn’t look like it’s all in the same file or in sequence as it appears in the question

  • Another thing, I can remove at the moment this comparison inside, just needed the attribution with the data from Survivor and the items to be inside the @Inventory but this does not happen.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.