/home/web-programming/rubyonrails/

Ruby on Rails: Setting Random Tokens

Replace URL id numbers (users/1) with token strings (users/9394skdfiekf1dd346) to keep your Ruby on Rails app from divulging information about your data, such as, how many users have signed up.

Step One: Database Setup

Step Two: Update app/models/ File

before_create :generate_token

def to_param
 token
end

private

def generate_token
 self.token = SecureRandom.urlsafe_base64
end

Step Three: Update Existing Data

If data already existings in the table migrated above, then migrate data to each item in the table by adding this to the migration file.

User.all.each do |user|
 user.token = SecureRandom.urlsafe_base64
 user.save
end

Step Four: Update app/controllers/ File

def show
 @user = User.find_by_token(params[:id])
end