Chris Martinez Chris Martinez - 8 months ago 33
Ruby Question

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?


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:

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


  def generate_unique_secure_token
    self.secure_token = SecureRandom.hex(24)

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])