【问题标题】:assigning random url to a resource in rails 3将随机 url 分配给 rails 3 中的资源
【发布时间】:2011-04-14 23:03:02
【问题描述】:

我需要为我的主题模型(例如)生成一个随机 URL:

http://localhost:3000/9ARb123

那么我如何在 Rails 中做到这一点?

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

【问题讨论】:

    标签: ruby-on-rails-3 random url-routing


    【解决方案1】:

    可能是这样的

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

    会将 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 
    

    【讨论】:

    • Patrick,这对我不起作用;在我创建了一个主题后,url 显示:(localhost:3000/topics/1) 我需要的是 url 在创建后应该是:localhost:3000/"random string"。请帮忙!
    • 仍在寻找答案:(
    【解决方案2】:

    Patricks 的回答应该有效 - 但它只涵盖路由传入请求。 如果您仍在使用标准路由(例如 topic_path)来创建链接,它仍将使用普通路由。

    如果您运行 rake 路由,您应该会看到您使用 random_id 创建的路由的名称。 (您可能需要使用 :as => 'random_route' 为其命名)

    如果你调用它而不是标准的 topic_path 你应该得到你所追求的路线

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多