Rixcy Rixcy - 4 months ago 11
Ruby Question

How to create a 'page counter' in a controller in rails

I have a Post model, and I'm wanting to implement a way of counting the amount of times a post has been visited through the posts_controller so that I can eventually order posts by view count. So far I've created a migration to add a 'view count' column to by Post model:

class AddViewcountToPosts < ActiveRecord::Migration
def change
add_column :posts, :view_count, :integer
end
end


I basically want something in the PostsController show method to add one on to the view_count column every time the show action is accessed.

Any help would be greatly appreciated :)

Answer

You can just increase this counter in your show action.

def show
  # ...
  @post.increment!(:view_count)
end

No magic here :)