4

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.

1
  • There have been some good answers, but you definately don't want to do this in your view, you are better off running it in your controller. Commented Mar 15, 2016 at 8:38

4 Answers 4

7

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
 =# ...... 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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!

Comments

0

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

user.increment!(:points, 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.