我正在设置routes.rb以支持不需要前缀的虚URL。例如,不需要mysite.com/articles/seo-url-here
中的“articles /”。我想要mysite.com/seo-url-here
如何设置routes.rb,以便当网址访问我的网站时:routes.rb会查看网址中seo-url-here
的值是否与表Article.seo_url
中数据库中的记录相匹配}。如果找不到匹配,则routes.rb应该向下移动其余的routes.rb文件。
由于
答案 0 :(得分:1)
帮助您入门的基本代码:
# 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
相关文章:Pretty, short urls for every route in your Rails app - Arkency Blog
搜索rails url constraint
似乎有所帮助。