Counting the page views

I try to find a way to count the pageviews in the database
In my show page i have

<%= @advert.views %>

In the model i have this

def views
self.views =+ 1

For now i only get number 1 when I view the page and the database won’t
count the views.
In the database the views stays at 0
How can i make the database counts 1 each time i visit the page.

Is this model just for counting?

You need to find the current record, then save your changes to get the
database to update.

You should perform this in a transaction to keep one view from
stomping on another. See ActiveRecord::Base::transaction class


On May 26, 11:14 am, GA Gorter [email protected]

for now i have placed the action into in the controller
this time with uptdate_attribute but without counting again.
Only 1

def showadvert
@advert = Advert.find(params[:id])
@advert.update_attribute “views”, @advert.views =+ 1

the transaction works tottaly different than update_attribute
so everything tried with transaction failed

There’s a cleaner way:
ActiveRecord::Base#increment! increases the passed attribute by 1 and
saves the record.

def showadvert
@advert = Advert.find(params[:id])

then you can just show it in your views as you suggested:

<%= @advert.views %>

Thanks for your help
I found a way to count it.
Because i was searching on transaction found update_advert

def showadvert
@advert = Advert.find(params[:id])
abc = @advert.views += 1
@advert.update_attribute “views”, abc