I have field called ads_counter in my database, and I need to increase its value each time when this ad is rendered.
I tried to write a custom method and use it in the controller responsible for this data, but that didn't work. Are there any built-in methods to increase the value of a field in the database?
Yes, there is the increment
method that you can call in your ActiveRecord.
For reference: increment
Edit:
To make it save directly use the increment!
You may use it this way:
instance.increment!(:ads_counter)
It automatically increments by 1
instance.increment!(:ads_counter, <number>)
It increments by number provided
You have the method increment!
that increments an attribute and saves the record
your_object.increment!(:ads_counter)
Put this code in the show
method of your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With