网址是 UI in Rails 5

URLs are UI in Rails 5

遇到这个 blog post recently and wanted to Incorporate its ideas into my Rails project - URLs should be short, human readable, shareable, and shorten-able. Specifically, I want to learn how to make URLs shorten-able with Rails. The example he gives is https://whosebug.com/users/6380/scott-hanselman and https://whosebug.com/users/6380 是相同的 URL,ID 后面的文本被忽略,scott-hanselman 将在导航到页面后添加。这提高了可读性和 share-ability.

我希望在我的资源 URLs 中的 show 操作到 auto-add 页面的 <title> 在导航到页面时在 ID 之后,但在用户将其粘贴到搜索栏中。这允许可延展的标题。

示例如下。所有这些 URL 应该将您带到 ID 为“1”

resource

host/resource/1/exciting-blog-post

host/resource/1

host/resource/1/exciting-blog-post.html

host/resource/1/new-title-on-post

编辑:

我遇到的最大困难是在用户提交后编辑URL,即将resource/1 转换为resource/1/name_column

我已经能够使用 config/routes.rb 中的以下内容重定向不正确的路由 - get "/events/:id/*other", to: redirect('events/%{id}')

好吧,这真的很难弄清楚,甚至不知道我以前可以访问很多这些参数。 FriendlyID 不是必需的,甚至不能解决这个问题。

我在下面使用的资源是"events"。

首先编辑您的 config/routes.rb 以接受 id/other_stuff

Rails.application.routes.draw do
  resources :events
  get "/events/:id/*other" => "events#show" #if any txt is trailing id, also send this route to events#show
end

如果 URL 不正确,接下来修改 event_controller.show 以重定向。

  def show
    #redirect if :name is not seen in the URL
    if request.format.html? 
      name_param = @event.name.parameterize
      url = request.original_url
      id_end_indx = url.index(@event.id.to_s) + (@event.id.to_s).length + 1 #+1 for '/' character
      ##all URL txt after id does not match name.parameterize
      if url[id_end_indx..-1] != @event.name.parameterize
        redirect_to "/events/#{@event.id}/#{name_param}"
      end
    end
  end

这将导致与问题中 Stack Overflow 示例完全相同的行为。