Forum: Ruby on Rails Counting the page views

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fa342466c787830ea65ffc638d22d9c4?d=identicon&s=25 GG9 Rails (gorter9)
on 2007-05-26 20: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
end

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.
588ab1c0a5610a7e160a3b101abb91e6?d=identicon&s=25 MichaelLatta (Guest)
on 2007-05-26 20: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
method.

Michael



On May 26, 11:14 am, GA Gorter <rails-mailing-l...@andreas-s.net>
Fa342466c787830ea65ffc638d22d9c4?d=identicon&s=25 GG9 Rails (gorter9)
on 2007-05-26 22: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
    end

the transaction works tottaly different than update_attribute
so everything  tried with transaction failed
Fa342466c787830ea65ffc638d22d9c4?d=identicon&s=25 GG9 Rails (gorter9)
on 2007-05-26 22: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
    end
D7c511ce5025d37b8c6bd9134e0f2bd9?d=identicon&s=25 Thorsten (Guest)
on 2007-05-27 13: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])
  @advert.increase!("views")
end

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

<%= @advert.views %>
This topic is locked and can not be replied to.