I have an Advert model that basically has an image, title and a url. I use CarrierWave for the image. Everything works well, but I am wanting to count impressions and clicks.
So far, I added two integer columns: impressions, clicks
I have a pages controller and have set an @advert variable that changes depending on the page. After reading this question I am able to increment impressions:
def index
@advert = Advert.sample
@advert.increment! :impressions
end
I am having trouble incrementing the clicks | Below is the code I need to modify so that when a user clicks on the image_tag they are taken to the URL as normal, but that the @advert increments the clicks column. Here is my current code (I use HAML and this is code is in a file: _advert.html.haml):
= link_to image_tag("#{advert.foto_url.to_s}",:alt => "an image ad linking to #{advert.url}", :title => advert.title), advert.url, :target => "blank"
What is the easiest, cleanest way to successfully increment! the clicks attribute on the Advert when someone clicks on the link above?
Update:
I am using the suggestion from Aaron below, but it leads to two new concerns:
-
The user will see a different link when they hold their mouse over the image than the final link they will end up at. I would prefer to have them see the final URL they will end up if they click rather than Redirecting simply to count their click.
-
If someone pulls up the advert url (eg: /adverts/1) directly the counter would increment! without a click.
I actually didn’t have a show view for Advert, but added it to get this done. So to be clear this works, but it feels like it violates best practices. Thank you though to Aaron.
I think the easiest way would be to make the advert image link to the advert show action, which could increment the counter and then redirect to the advert url.
In your link, change
advert.urltoadvert_path(advert)(and set up the necessary route) then inadverts_controller: