将随机 url 分配给 rails 3 中的资源

ios*_*gcd 5 random url-routing ruby-on-rails-3

我需要为我的主题模型(例如)生成一个随机 url,如下所示:

http://localhost:3000/9ARb123

那么我怎样才能在 Rails 中做到这一点呢?

注意:随机字符串必须包含数字、小写和大写字母。

Pat*_*son 4

也许是这样的

#config/routes.rb
match "/:random_id" => "topics#show", :constraints => {:random_id => /([a-zA-Z]|\d){3,6}/}
Run Code Online (Sandbox Code Playgroud)

会将 3-6 个随机字母/数字组成的随机字符串与主题控制器的 show 方法相匹配。确保在此匹配器之上声明其他资源,因为类似“http://localhost:3000/pies”的内容将路由到 Topics#show 而不是 Pies#index。

要为您的主题生成随机 URL,您可以执行以下操作:

#app/models/topic.rb
before_create :generate_random_id

def generate_random_id
   #generates a random hex string of length 6
   random_id = SecureRandom.hex(3)
end 
Run Code Online (Sandbox Code Playgroud)