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))
任何想法?我已經嘗試了其中的一些;
- http://blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app/
- How to remove controller names from rails routes?
- http://base0.net/posts/two-ways-for-rails-multiple-model-url-aliases/
但他們並沒有完全奏效了爲止。謝謝:)♥
如何做了限制SOLU在http://blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app/中描述的不工作? –
錯誤在我身邊,我實際上已經能夠使用您的解決方案解決問題! –
很高興聽到它。祝你今天愉快! –