M1xelated
M1xelated

Reputation: 169

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.

Upvotes: 4

Views: 2044

Answers (4)

Fellow Stranger
Fellow Stranger

Reputation: 34013

Add an exlamation mark to Зелёный's answer and the object gets updated directly as well:

user.increment!(:points, 1)

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

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
 =# ...... 

Upvotes: 7

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Create a member action to perform the increment task

def increase_points
  user = User.find_by(id: params[:id])
  user.update_attributes(points: (user.points + 100))
end

Hope this helps!

Upvotes: 0

Typpex
Typpex

Reputation: 608

If you want to increase the value when a user is doing a certain action, then you should update points in the controller when the given action is triggered.

Class MyController
  def given_action
    @user.update_attributes(points: new_value)
  end
end

Upvotes: 0

Related Questions