Count number of downloads and link_to

Hello,

I have a download link on my page, whick looks like that :

<%=link_to “Download”, @photo.public_filename, :class => “thickbox”%>
As you see, I m displyaing an image in a thickbox popup. However I
would like to count the number of times the user clicks on this link,
to get a number of downloads, and so increment a value in my db each
time the link is clicked. But how can I achieve this. Is there a way
to couple an ajax call to this link ?

Also, I want to display the number of downloads for " today ". Anyone
has an idea of how I can do this.

Thx in advance,

Regards

Hmmm, off the top of my head I would say add two fields to the photo
model, one ‘download_count_total’, and ‘download_count_today’. Then
write a helper function link_to_with_count that would look something
like:

def link_to_with_count(name, model, options)
model.update_attributes(:download_count_total =>
model.download_count_total.next,
:download_count_today => model.download_count_total.next)
link_to name, model, options
end

Then, you would need to write a script that runs every night at
midnight and resets every photos download_count_today attribute.

What’s the last line code used to ?

" link_to name, model, options "

Thx,

Joel

“named_route :todays_downloads, {:conditions => {:created_at =>
Date.today}}” should just be
“named_route :todays_downloads, :conditions => {:created_at =>
Date.today}”. (Where the heck’s the edit button?)

First I’d create a column in the table that’s storing your photos
named “download_count”. Then add a line to your routes file, something
like “yourcontroller/update_download_count/:id/:count”, then create an
action in the controller:

def update_download_count
YourModel.update_attribute :download_count, params[:count] + 1
end

and finally, change your link to:
<%=link_to_remote “Download”, @photo.public_filename, :url => {:action
=> update_download_count, :id => @photo.id, :count =>
@photo.download_count}, :html => {:class => “thickbox”} %>

And to display today’s downloads, add a named route to your model:
named_route :todays_downloads, {:conditions => {:created_at =>
Date.today}}

Just something quick I thought up, it should help you get on the right
track :slight_smile:

Sorry, named_route should be named_scope, and the outer { } should be
removed from it.