如何让 URL 中的 id 是随机的?

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

所以我正在寻找一种创建随机 ID 的方法,该 ID 将 link 发送到将在 rails 中调用显示方法时显示的大厅。截至目前,url 看起来像这样:http://localhost:3000/lobby/2。我希望用随机生成的 ID 替换那个 2,这样如果您希望朋友加入您的大厅,您可以将 link 发送给他们。有任何想法吗?

我不会给你完整的答案,因为学习这些东西很棒,但如果你有任何问题,请随时问我!

这是你应该开始的地方:URLSafe Base 64

Here's a Railscasts episode 很软,和你想要的差不多,看看你能不能从那里扩展!如果您是 Rails 的新手,请务必查看 Railscasts。所有专业剧集均可在 youtube 上免费观看!

您应该像 Gavin 所说的那样分享更多信息。了解您已经尝试过的内容可以帮助我们为您提供有关如何继续的 more/better 信息。

我希望这能为您指明正确的方向。要生成随机 ID,您可以使用 SecureRandomhttp://ruby-doc.org/stdlib-1.9.3/libdoc/securerandom/rdoc/SecureRandom.html

我建议您在 lobbies table 中再添加一列,并使其独一无二:

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

现在,在您的 Lobby 模型中,无论何时创建它,您都可以生成一个唯一的令牌。为简单起见,您可以按照以下方式执行操作:

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

这将在每次创建 Lobby 时生成一个 secure_token。现在在控制器中,您可以使用 secure_token 而不是 id 来找到您的 Lobby。例如:

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