0

I'm working on getting a pay per click system running on my app, and I've been able to get some help in setting up the framework here on SO. Here's what I've got so far:

class Click < ActiveRecord::Base
    belongs_to :deal
    belongs_to :vendor
end

class ClicksController < ApplicationController
    def create
        @deal = Deal.find(params[:deal_id])
        @deal.clicks.create
    end
end

class Deal < ActiveRecord::Base
    belongs_to  :vendor
    has_many    :clicks
end

I want to be able to call my create method anytime I have a link_to a deal resource. On clicking the user will be taken to that deals view, so I don't want to replace the default method in link_to. Is there a way to call a second method on link_to? Or perhaps using javascript would be a better solution? To be honest, I'm relatively new to RoR, and I don't know much javascript at all. Any suggestions on how best to accomplish this? Thanks in advance!

settheline
  • 3,333
  • 8
  • 33
  • 65

1 Answers1

1

It sounds like you want the following:

  • a user clicks a link that would lead to a Deal
  • a Click is created for that Deal
  • the user sees the Deal's page

I think there are two decent ways to do this. One is to treat the links as buttons that do a POST to the ClicksController. The other is to have an after_filter on the DealsController.

The former would mean changing your links to point to the ClicksController, use POST (which by default directs to the #create action), and have a redirect at the end of the #create action to

redirect_to @deal

See link_to docs for more info.

This feels more RESTful, though the link_to might be a bit ugly-looking.

The latter option means adding something like

after_filter -> { @deal.clicks.create }

for the DealsController#show method.

Davd_R
  • 384
  • 4
  • 10
  • Good thoughts, I went with something similar to the first suggestion. I ended up using a form_for. Appending all the params into a link_to + changing method and action seemed to be getting a little messy. Didn't want to deal with making a button_to work when I need the button to be an image. Thanks for the answer! – settheline Nov 13 '13 at 04:04