I’m making a “click counter”, i.e, when a user clicks a button, we want to count the clicks. In my case, the user is visiting a page for coupons, and I want to count the number of time she clicks the print button.
To set this up, I created a “click” model.
class Click < ActiveRecord::Base
belongs_to :coupon
end
And a click controller with a create method.
class ClicksController < ApplicationController
def create
@coupon = Coupon.find(params[:id])
@coupon.clicks.create
respond_to do |format|
format.html { redirect_to @coupon }
end
end
end
And I’ve created a migration like this:
class CreateClicks < ActiveRecord::Migration
def self.up
create_table :clicks do |t|
t.integer :coupon_id
t.timestamps
end
end
def self.down
drop_table :clicks
end
end
Then I configure my routes like so:
map.resources :coupons, :has_many => :clicks
map.resources :clicks
map.connect 'coupons/:id/clicks', :controller => 'clicks', :action => 'create'
And then the button that ads 1 click:
<%form_remote_tag :url => coupon_clicks_path(@coupon) do %>
<% submit_tag 'click!' %>
<% end %>
Then I browse to /coupons/4/clicks …. and it gives me an error saying that it can’t find the page. What am i doing wrong?
As @Matthew mentioned it looks like you’re using Rails 2, the reason your route isn’t recognized is that you’re defining it after the resources of coupons. They both share the part of the route ‘/coupons’ so that resource’s REST routes are overriding
'coupons/:id/clicks'.As is says in the routes.rb default comments: The priority is based upon order of creation, first created -> highest priority.
So to get your
'coupons/:id/clicks'route to of a higher priority move it to the top of the routes.rb file.