Rails add parameter to each URL in the application
Asked Answered
C

3

11

I would like to add a parameter to each URL in my Rails 2.3.10 application. I played with the default_url_options but I want the parameter to be visible in the URL. Something like:

http://<server>/posts?token=XYZ

I'm building an affilate tracking system and I want people to share the link and be able to track who's link was used later when someone clicks it (to give points to the guy who shared the link). Any hints how I can add a visible parameter in each URL used in the application?

Thanks!

Charr answered 5/11, 2010 at 12:24 Comment(0)
H
5

Rewrite url_for

module ActionView::Helpers::UrlHelper
  def url_for options
    options.merge! {:token => generate_token}
    super
  end
end

or just add this to your application.rb file

config.default_url_options += {:token => proc{generate_token}}
Hagiolatry answered 5/11, 2010 at 13:9 Comment(2)
I went for the default_url_options in the application_controller.rb as your first solution doesn't seem to work for me (the merge method doesn't exist for an array and apparently args is an array). Thanks for the help!Charr
Whoops, my bad. I guess I fixed it now.Hagiolatry
T
2

define default_url_options in ApplicationController (or the relevant controller)

def default_url_options
  {subdomain: 'www'}
end
Tamikotamil answered 10/9, 2013 at 21:14 Comment(0)
N
0

I would use the users login, or generate a token which you store as a field in the user table then add that to the url as so:

post_path(@post, :token => user.token)

If you want the token to be unique to the post then similarly include a post token:

#post.rb
def generate_token user
  "#{self.token}-#{user.token}"  

#view
post_path(@post, :token => post.generate_token)
Nopar answered 5/11, 2010 at 12:57 Comment(1)
Thanks for the reply Mark but the token I have, that's not the problem. My question was about adding the token to each URL and not having to pass the token param every time like you show.Charr

© 2022 - 2024 — McMap. All rights reserved.