Rails Controller update subtract 1 from value

74 Views Asked by At

How can I subtract 1 from a value in a Rails Controller it's easy in Postgresql

 Update junkcars
 Set junkcartotal = junkcartotal -1
 Where id = 5161

In a rails controller I tried

Junkcars.update(junkcartotal: junkcartotal -1).where(id: 5161)

I get nothing but errors.

2

There are 2 best solutions below

0
Alex On BEST ANSWER

It's easy in rails too:

Junkcar.find(5161).decrement!(:junkcartotal)

https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-decrement-21

3
Benjamin Scharbau On
@junk_car = Junkcar.find(5161)
@junk_car.update(junkcartotal: @junk_car.junkcartotal - 1)