Forum: Ruby on Rails Counting the page views

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
GG9 R. (Guest)
on 2007-05-26 22:14
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.
MichaelLatta (Guest)
on 2007-05-26 22:44
(Received via mailing list)
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 <removed_email_address@domain.invalid>
GG9 R. (Guest)
on 2007-05-27 00:08
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
GG9 R. (Guest)
on 2007-05-27 00:13
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
Thorsten (Guest)
on 2007-05-27 15:17
(Received via mailing list)
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 %>
This topic is locked and can not be replied to.