Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails. Increase integer in database

I have created a website using Ruby on rails and have a database with points for my users. Every user has points so I would refer to it as @user.points. I am able to view the points by using:

<%= user.points %>

I am trying to increase these points from my page as users complete a certain action. So I tried doing:

<% @user.points += 100 %>

but this doesn't seem to work. I feel there is a simple solution or I am overseeing something.

like image 802
M1xelated Avatar asked Oct 20 '25 14:10

M1xelated


1 Answers

You can use increment(attribute, by = 1):

Initializes attribute to zero if nil and adds the value passed as by (default is 1). The increment is performed directly on the underlying attribute, no setter is invoked. Only makes sense for number-based attributes. Returns self.

@user.increment(:points,  100)

Example:

 => user = User.last
 => user.points
 =# 100
 => user.increment(:points, 100)
 => user.points
 =# 200
 => user.increment(:points, 100)
 => user.points
 =# 300
 =# ...... 
like image 60
Philidor Avatar answered Oct 22 '25 04:10

Philidor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!