簡體   English   中英

如何在不需要前綴的情況下為虛名 URL 設置 Rails routes.rb

[英]How to setup Rails routes.rb for Vanity URL without requiring a prefix

我希望設置 routes.rb 以支持不需要前綴的虛 URL。 例如,不需要mysite.com/articles/seo-url-here的“articles/”。 我只想要mysite.com/seo-url-here

如何設置 routes.rb 以便當 url 訪問我的站點時: routes.rb 會查看seo-url-hereseo-url-here的值是否與表Article.seo_url中我的數據庫中的記錄匹配。 如果發現不匹配,則 routes.rb 應該向下移動到 routes.rb 文件的其余部分。

幫助您入門的基本代碼:

# config/routes.rb

Rails.application.routes.draw do
  resources :posts
  resources :authors

  constraints(PostUrlConstrainer.new) do
    get "/:id", to: "posts#show"
  end
end

# app/constraints/post_url_constrainer.rb

class PostUrlConstrainer
  def matches?(request)
    title = request.path_parameters[:id]
    Post.find_by(title: title)
  end
end

# app/controllers/posts_controller.rb

def set_post
  @post = Post.find_by(title: params[:id])
end

相關文章: Rails 應用程序中每條路線的漂亮短網址 - Arkency 博客

搜索rails url constraint似乎有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM