如何为虚荣URL设置Rails routes.rb,无需前缀

时间:2017-01-02 00:19:05

标签: ruby-on-rails ruby ruby-on-rails-4 seo rails-routing

我正在设置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文件。

由于

1 个答案:

答案 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似乎有所帮助。