Texas
Texas

Reputation: 913

Problem Counting Number of Times a Link is Clicked in Rails

I have a database with a number of records in it, each with an associated URL. Currently I have things set up so that when people click on a link for a particular record they get redirected to the appropriate URL. The code is currently:

<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link %>

This does its job fine. I would like to now modify this so when the link is clicked on, a parameter called :click_count which is orignally set to 0 for all records.

Reading around, I believe you can do this using something of the following form:

<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link, {:controller => params[:controller], :action => "clickcountplusone", :product_name => alldata.product_name}  %>

With the following in the controller:

def clickcountplusone
  clickeditem = Entiredatabase.find(params[:product_name])
  clickeditem.update_attribute(:click_count => clickeditem.click_count + 1)
end

Although this does not produce an error, it also doesn't increase the count number... Could anyone shed any light on the issue?

Upvotes: 0

Views: 1054

Answers (2)

JCorcuera
JCorcuera

Reputation: 6834

Your sintax on update_attribute is wrong:

clickeditem.update_attribute(:click_count => clickeditem.click_count + 1)

should be:

clickeditem.update_attribute(:click_count, clickeditem.click_count + 1)

Be carefull, update_attribute receives a (name, value) and update_attributes receives a hash. More information here

Also take a look to increment counter

Item.increment_counter(:click_count, @item.id)

Upvotes: 0

Frankie Roberto
Frankie Roberto

Reputation: 1359

You shouldn't really need a separate action for this. Instead, simply use the default show action, and increment the counter whenever the action is called, like this:

def show
   @item = Item.find(params[:id])
   Item.increment_counter(:views, @item.id)
end

This will however increment the counter whenever that page is viewed - so if you want to only track views that followed a particular link, you could do something like:

def show
   @item = Item.find(params[:id])
   if params[:from_link]
     Item.increment_counter(:views, @item.id)
   end
end

And then in your link_to helper, add an extra param:

link_to(image_tag("blah.jpg"), item_path, {:from_link => true}

Hope this helps.

Upvotes: 1

Related Questions