Alex
Alex

Reputation: 419

Setting up an invite friends link

I am trying to build out a feature where you can invite your friends with a customer url. I added a column to my user model such that when a user signs up, it will give them a unique token that will track back to them when the link is shared.

User.rb:

def set_referer_url
  begin
    self.referer_url = rand(36**8).to_s(36)
  end while User.exists?(:referer_url => self.referer_url)
end

I then set up a mailer that will send friends an invitation with the following url:

www.nameofsite.com/r/[referer_url]

I have set up the route as follows:

match '/r/:referer_token' => 'users#new'

I have a column in my user model called referer where I want to record if the user signed up through someone's invitation link. If so, the referer column should specify the user ID of the person who referred them.

I have the following for the sign_up view:

<%= form_for @user, :as => :user, :url => {:controller => "users", :action => "create" } do |f| %>
  <%= f.hidden_field :referer_token %>

  <p>
  <%= f.label :email %><br />
  <%= f.text_field :email %>
  ...

In my user model I have the following to attempt to assign the referer ID to a new user:

def referer_token
  User.referer_url if user
end

def referer_token=(token)
  self.referer = User.find_by_referer_url(token).id
end

AND

attr_accessible :email, :password, :password_confirmation, :referer_token

I thought that this would find the referer's ID via the url and set it in the column of referer for the new user. This does not seem to be happening. I don't think that the parameter of referer_token is passing through the form, so that the referer's ID can be stored. How can I fix this?

Upvotes: 0

Views: 664

Answers (1)

Chap
Chap

Reputation: 3563

You're close, but I'd probably do the association in the controller and define the association in the model:

# models/user
class User < ActiveRecord::Base
  belongs_to :referrer, :class_name => 'User'
  # you'll need a referrer_id on your users table
end

# views/users/new
<%= form_for(@user) do |f| %>
  <%= hidden_field_tag :referrer_token, params[:referrer_token] %>
  ...

# controllers/users_controller
class UsersController < ApplicationController
  @user = User.new(params[:user])
  @user.referrer = User.find_by_referrer_url(params[:referrer_token])
  @user.save
end

Then you can do:

@user.referrer => #<User id: 114...

Upvotes: 1

Related Questions