2016-10-04 77 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" 

最終

相關問題