在rails 3中为资源分配随机url

| 我需要为我的Topic模型生成一个随机URL,例如:   http://本地主机:3000 / 9ARb123 所以我该怎么做呢? 注意:随机字符串必须包含数字,小写和大写字母。 提前致谢。     
已邀请:
像这样的东西
#config/routes.rb
match \"/:random_id\" => \"topics#show\", :constraints => {:random_id => /([a-zA-Z]|\\d){3,6}/}
会将3-6个随机字母/数字的随机字符串与Topics控制器的show方法匹配。确保声明此匹配器之上的其他资源,因为\“ http:// localhost:3000 / pies \”之类的内容将路由到Topics#show而不是Pies#index。 要为您的主题生成随机网址,您可以执行以下操作:
#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 
    
帕特里克(Patricks)的回答应该有效-但它仅涵盖路由传入的请求。 如果您仍在使用标准路由(例如topic_path)创建链接,则它仍将使用常规路由。 如果运行耙式路由,则应该看到使用random_id创建的路由的名称。 (您可能需要使用:as => \'random_route \'来命名它) 如果您调用它而不是标准的topic_path,那么您应该得到的路线是     

要回复问题请先登录注册