Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing counter in database

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?

like image 999
Avdept Avatar asked Oct 25 '12 13:10

Avdept


2 Answers

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

like image 156
felipeclopes Avatar answered Oct 19 '22 22:10

felipeclopes


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.

like image 30
Baldrick Avatar answered Oct 19 '22 23:10

Baldrick