Chris Martinez
Chris Martinez

Reputation: 89

How can you make the id in the URL be random?

So I am looking for a way to create a randomized id that will link to a lobby that will be shown when the shown method is called in rails. As of right now, the url would look like this: http://localhost:3000/lobby/2. I'm looking to replace that 2 with a randomly generated id so you could send that link to friends if you want them to join your lobby. Any ideas?

Upvotes: 0

Views: 448

Answers (2)

Alex Santos
Alex Santos

Reputation: 2950

You should share a bit more information as Gavin said. Knowing what you have already tried can help us give you more/better information on how to proceed.

I hope this sends you the right direction. For generating random IDs you can use SecureRandom: http://ruby-doc.org/stdlib-1.9.3/libdoc/securerandom/rdoc/SecureRandom.html

I'd recommend you add another column to the lobbies table, and make it unique:

add_column :lobbies, :secure_token, :string, null: false
add_index :lobbies, :secure_token, unique: true

Now, in your Lobby model, whenever it is created, you can generate a unique token. For simplicity, you can do something along these lines:

class Lobby < ActiveRecord::Base
  before_create :generate_unique_secure_token

  # Rest of the model's code

  private


  def generate_unique_secure_token
    begin
      self.secure_token = SecureRandom.urlsafe_base64
    end while self.class.exists?(secure_token: secure_token)
  end
end

This will generate a secure_token every time a Lobby is created. Now in the controller you can use the secure_token instead of the id to find your Lobby. For example:

class LobbiesController < ApplicationController 
  def show
    @lobby = Lobby.find_by(secure_token: params[:id])
  end
end

Upvotes: 2

Kieran E
Kieran E

Reputation: 3666

I won't give you the whole answer since it's great to learn these things, but if you have any questions feel free to ask me!

This is where you should start: URLSafe Base 64

Here's a Railscasts episode that's soft of similar to what you want, see if you can expand from there! If you're new to Rails, be sure to check out Railscasts. All the pro episodes are available for free on youtube!

Upvotes: 0

Related Questions