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/中描述的不工作? –
错误在我身边,我实际上已经能够使用您的解决方案解决问题! –
很高兴听到它。祝你今天愉快! –