[英]How to setup Rails routes.rb for Vanity URL without requiring a prefix
I'm looking to setup routes.rb to support vanity URLs that do not require a prefix.我希望设置 routes.rb 以支持不需要前缀的虚 URL。 For example not requiring the "articles/" in
mysite.com/articles/seo-url-here
.例如,不需要
mysite.com/articles/seo-url-here
的“articles/”。 I want just mysite.com/seo-url-here
我只想要
mysite.com/seo-url-here
How can I setup routes.rb so that when a url hits my site: routes.rb looks to see if the value of seo-url-here
in the url matches a record in my database in the table Article.seo_url
.如何设置 routes.rb 以便当 url 访问我的站点时: routes.rb 会查看
seo-url-here
中seo-url-here
的值是否与表Article.seo_url
中我的数据库中的记录匹配。 If not match is found, then routes.rb should move on down through the rest of the routes.rb file.如果发现不匹配,则 routes.rb 应该向下移动到 routes.rb 文件的其余部分。
Basic code to get you started:帮助您入门的基本代码:
# 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
Related article: Pretty, short urls for every route in your Rails app - Arkency Blog相关文章: Rails 应用程序中每条路线的漂亮短网址 - Arkency 博客
Searching for rails url constraint
seems to help.搜索
rails url constraint
似乎有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.