2016-10-04 78 views
0

我在我的应用程序中有两个型号:文章页面。我希望网址看起来像这样;如何从多个Rails路径中删除控制器名称?

www.mysite.com/this-is-the-title-of-the-article (articles#show) 
www.mysite.com/about-me (pages#show) 

有点类似于普通的wordpress路由,但是用rails这个看起来很麻烦。我找到了一个可行的解决方案,但它可能会改进。这是我得到的;

Inside routes.rb;

resources :articles, :pages 
    # this redirects /:id requests to my StaticPagesController 
    match ':id' => 'static_pages#redirect', :via => [:get] 
    resources :articles, :only => [:show], :path => '', as: "articles_show" 
    resources :pages, :only => [:show], :path => '', as: "pages_show" 

内StaticPagesController;

# Basically, it checks if there's a page or article with the given id and renders the corresponding show. Else it shows the 404 
    def redirect 
     @article = Article.where(slug_nl: params[:id]).first || Article.where(slug_en: params[:id]).first 
     @page = Page.where(slug: params[:id]).first 
     if [email protected]? 
      @page = Page.friendly.find(params[:id]) 
      render(:template => 'pages/show') 
     elsif [email protected]? 
      @article = Article.friendly.find(params[:id]) 
      @relatedarticles = Article.where(category: @article.category).uniq.limit(6).where.not(id: @article) 
      render(:template => 'articles/show') 
     else 
      render(:template => 'common/404', :status => 404) 
     end 
     end 

注:我已经换出的文章和网页的标题属性的ID(使用friendly_id宝石)。文章也是两种语言(因此我检查两个slu))

任何想法?我已经尝试了其中的一些;

但他们并没有完全奏效了为止。谢谢:)♥

+1

如何做了限制SOLU在http://blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app/中描述的不工作? –

+0

错误在我身边,我实际上已经能够使用您的解决方案解决问题! –

+0

很高兴听到它。祝你今天愉快! –

回答

0

我改进了解决方案,但它仍然感觉不到100%rails-y。但是,这是我所做的,

  • /页标题(页#显示)
  • EN /本,是最文章(文章#秀,EN 区域)
  • NL /二叔是德-titel (文章#秀,NL区域)

注:我已经换出的文章和网页的标题属性的ID(使用friendly_id宝石)。这些文章也是两种语言(因此我检查两个slu))

Routing.rb(修改自blog.arkency。COM/2014/01 /短网址,换每个路由,在你的Rails的应用

resources :users, :projects, :testimonials, :articles, :pages 
    class ArticleUrlConstrainer 
    def matches?(request) 
     id = request.path.gsub("/", "")[2..-1] 
     @article = Article.where(slug_nl: id).first || Article.where(slug_en: id).first 
     if I18n.locale == :en 
     @article = Article.find_by(slug_en: id) || Article.find_by(slug_nl: id) 
     else 
     @article = Article.find_by(slug_nl: id) || Article.find_by(slug_en: id) 
     end 
    end 
    end 

    constraints(ArticleUrlConstrainer.new) do 
    match '/:id', :via => [:get], to: "articles#show" 
    end 

    class PageUrlConstrainer 
    def matches?(request) 
     id = request.path.gsub("/", "")[2..-1] 
     @page = Page.friendly.find(id) 
    end 
    end 

    constraints(PageUrlConstrainer.new) do 
    match '/:id', :via => [:get], to: "pages#show" 
    end 

    resources :articles, :only => [:show], :path => '', as: "articles_show" 
    resources :pages, :only => [:show], :path => '', as: "pages_show" 

最终

相关问题