问题描述:

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.

相关阅读:
Top