kostasew
kostasew

Reputation: 93

Can i do simple maths in Active Record Ruby on Rails

i want to change the quantity of the item when the user saves a invoice i use something like that Item.find_by(itemName: 'kimas').update(:quantity => +7) and for some reason it replace the old value, for example if the value is 10 and run this Item.find_by(itemName: 'kimas').update(:quantity => +7) the value change to 7

class Invoice < ApplicationRecord
        before_save :check_me
        before_update :check_me

    def check_me
        items = itemname.length
        i = 0
        while i < items
        item_new = Item.find_by(itemName: itemname[i])
        sumup = ( quantity[i] * price[i] + (quantity[i] * price[i] * tax[i]/100) )
        Item.find_by(itemName: 'kimas').update(:quantity => +=7)
        i += 1
        end
    end
end

Upvotes: 0

Views: 54

Answers (2)

Olkin
Olkin

Reputation: 181

Unfortunately, you can only set a new value using Active Record's update.

In your case update(:quantity => +=7) will actually raise syntax error, unexpected operator-assignment).

The other form that you've used in this question update(:quantity => +7) is actually equivalent to update(:quantity => 7), and is same as update(quantity: 7). +7 is just another way of saying 7. As you've noticed this operation indeed only sets the new value to 7.

To solve your problem you could split your 1-liner into 2 lines:

  1. store the item you've found in a variable
  2. use variable's previous value to do your calculation

E.g. replace Item.find_by(itemName: 'kimas').update(:quantity => +=7) with:

item = Item.find_by(itemName: 'kimas')
item.update(quantity: item.quantity + 7)

Another option will be creating raw SQL code, but probably will be overkill for your situation.

Upvotes: 2

ellitt
ellitt

Reputation: 833

Calling update like that is going to set that value to whatever you pass it and attempt to match the data type found on the quantity column (which I assume is integer), which is why you're getting 7 and not 17.

You can try something like this instead:

found_item = Item.find_by(itemName: 'kimas')
found_item.update(quantity: found_item.quantity + 7)

Upvotes: 1

Related Questions