Skip to main content
 首页 » 编程设计

ruby-on-rails中Rails 如何生成类似 Google Drive 的永久链接

2024年11月24日69JustinYoung

当我们共享 Google 云端硬盘表单时,它会提供我们的公共(public)网址。

我们如何在 Rails 应用程序中实现这一点?它应该是随机的并且不重复。

有人可以帮助我吗?谢谢。

更新

我的意思是像这个网址:

https://docs.google.com/forms/d/1PPVIMrDo61Er9tqYlJRntfNT73jpxtd_YJGGjXOMlAw/edit?usp=drive_web

但我想要一个像这样的形式的网址:

http://yourhost.com/1PPVIMrDo61Er9tqYlJRntfNT73jpxtd_YJGGjXOMlAw

请您参考如下方法:

您应该向要共享其显示操作 URL 的模型添加一个永久链接 字段。实际上,您可以只使用 /model/:id 但如果您想使用 /model/:permalink 那么只需添加新字段,使用类似 的内容生成永久链接>SecureRandom 并将其保存到模型中,然后构建 URL 并共享。

你可以这样做:

class SomeModel < ActiveRecord::Base 
  after_create :generate_permalink 
 
  private 
 
  def generate_permalink 
    self.permalink = SecureRandom.urlsafe_base64(32) 
  end 
end 

然后在某些 View 中,您的用户可以找到永久链接网址:

<%= link_to "Title of the model", some_model_url(some_model.permalink) %> 

上面的帮助器将创建一个 URL,该 URL 转到 some_model Controller 的 show 操作。当然,如果您愿意,您可以创建一个新操作并将其添加到您的 route ,但我只是采用更简单的方法。

在 Controller 的显示操作中,您需要通过其永久链接找到模型:

class SomeModelController < ApplicationController 
  def show 
    @some_model = SomeModel.where("id = :id OR permalink = :id", id: params[:id]).first 
  end 
end 

通过对路线和 View 进行更多调整,您可以将 URL 缩短为您在问题中发布的内容:

http://yourhost.com/1PPVIMrDo61Er9tqYlJRntfNT73jpxtd_YJGGjXOMlAw 

要实现此功能,您必须将路由添加到 routes 文件的底部,以便在没有其他路由匹配时,您的永久链接路由将捕获随机字符串并分派(dispatch)它到您选择的 Controller :

# config/routes.rb 
get "/:permalink", to: "some_model#show", as: :permalink 

这里的参数在 Controller 中将被称为 params[:permalink] 而不是 params[:id] 。您可以通过使路由 get "/:id" 来简化 Controller 中的代码,但我认为明确一点是件好事。

然后,只需更改 View 即可输出正确的 URL:

<%= link_to "Title of the model", permalink_url(some_model.permalink) %> 

希望有帮助。