Sum a value in a field with Rails

Asked

Viewed 305 times

2

Hello! In my users table I have a field of downloads. I would like when the user enters the page I add +1 in this field of the user.

What is the best way to do this? Do I really need to make 2 querys? take the current value and then add another, or there is a way to simply add a value to that already existing value?

  • How did you do the authentication part with the user? With Devise? Why in this case it only loads the User object once and then keeps in cache.

  • yes, with the

1 answer

0


If you pay attention to us logs, will see that the Devise only searches for the user (SELECT ... FROM usuarios ...) once in the request, and then returns from cache if requested.

So there will be no problem in using:

current_usuario.downloads + 1

to update. Try one of the approaches, if it doesn’t work let me know:

current_usuario.downloads = current_usuario.downloads + 1
current_usuario.save

# ou
Usuario.update(current_usuario.id, downloads: (current_usuario.downloads + 1))
  • Hello. It didn’t work. it doesn’t update. Don’t give any error and at the prompt tbm shows no query referring...

  • @Igormartins I updated, tell me if it worked later.

  • Useri the first method, it worked!!! thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.