How to make read-times counter

Hello all:

I wanted to realize a article counter function in my blog system.

Please help me out
Thanks!

Devine A. wrote:

Hello all:

I wanted to realize a article counter function in my blog system.

Please help me out
Thanks!

Add a field to your blog posts table called read. Make it an int.

Every time your controller show action is called, update this count.

def show
@post = Post.find(params[:id])
@post.update(:read_count = @post.read_count +1)
end

Or something similar.

Simple, but not very efficient.

uhm …

add a “times_read” integer column to your articles table

in your controller, you add something like this:

#controller
def show
@post = Post.find params[:id]
@post.increment!(“times_read”)

… rest of your code …

end

#view

This Post has been read <%= @post.times_read %> times

On 8 Mai, 16:30, Devine A. [email protected]

Thorsten wrote:

uhm …

add a “times_read” integer column to your articles table

in your controller, you add something like this:

#controller
def show
@post = Post.find params[:id]
@post.increment!(“times_read”)

… rest of your code …

end

#view

This Post has been read <%= @post.times_read %> times

On 8 Mai, 16:30, Devine A. [email protected]

Thanks for your help!

The increment! can increments the attribute and saves the record.

def increment!(attribute)
increment(attribute).update_attribute(attribute, self[attribute])
end

One function can made it!
Rails is very perfect!