DanielNordby
DanielNordby

Reputation: 579

How do I access the ref portion of a URL in rails before redirect?

I had some code that was working that now seems to be broken, and I'm trying to hunt down why. It seems the issue focuses partially around my referral system.

Once a user signs up, they are given a unique referral code i.e. http://localhost:3000/?ref=b9270b78a6 (from my local machine). They can, in theory, then pass this on to their friends, and when their friends come to the site via their referral URL, I log the ref and credit the initial user with +1 referral.

While it was working, the URL came in, the program issues a GET command for "/?ref=b9270b78a6" and was redirected to '/frontpage' but the ref was stored as params[:ref]. Now params[:ref] is blank, and it's basically making my program say that no one referred anyone else.

It seems that I've deleted something important unintentionally, but I don't know what.

My problem is that a) I don't know how to capture the 'b9270b78a6' as prams[:ref], and on top of that it seems that I'm losing my chance to do that as the redirect points the browser to a generic URL and executes the 'StaticPagesController#frontpage' controller action before I could grab the code anyways:

Started GET "/?ref=b9270b78a6" for ::1 at 2015-10-20 16:19:36 -0400
Started GET "/frontpage" for ::1 at 2015-10-20 16:19:36 -0400
Processing by StaticPagesController#frontpage as HTML

In short: any idea on how I grab the ref code and saving it as params[:ref]?

I don't even know what code (controller, model, view) you might need to see to get to the bottom of this, so happy to update with whatever might be useful. My closest stab in the dark is that I'll need to use URI::parse(url) to then parse the incoming URL, but again - by the time I could potentially do that it's been redirected and I cannot.

Any thoughts are much appreciated!

Upvotes: 0

Views: 300

Answers (2)

Mark Swardstrom
Mark Swardstrom

Reputation: 18130

Glad you found the cause. Some of those errors are very hard to find with the usual debugging methods.

Btw - another tip. Throw the ref in a session - you can do this with a before action in the application controller and then the ref value will be available when you need it.

# application_controller.rb
before_action :set_ref

def set_ref
  session[:ref] ||= params[:ref] if params[:ref]
end

Then later you can get it when you save

referring_user_id = session[:ref]

Upvotes: 2

DanielNordby
DanielNordby

Reputation: 579

False alarm everyeone...it was my routes. What the heck...I haven't changed those in 8 weeks, and they break suddenly. Not to mention it was the most innocuous little route. Absolutely no reason this should have happened, but Happy Rails, it did.

Thanks to @Swards for your help, and for the learning experience!

Upvotes: 0

Related Questions