我的应用中有两个型号:文章和页面。我希望网址看起来像这样;
www.mysite.com/this-is-the-title-of-the-article (articles#show)
www.mysite.com/about-me (pages#show)
有点类似于普通的wordpress路线,但有了轨道,这似乎是一个很大的麻烦。我找到了一个可行的解决方案,但它可能会得到改进。这就是我得到的;
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"
Inside 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 !@page.nil?
@page = Page.friendly.find(params[:id])
render(:template => 'pages/show')
elsif !@article.nil?
@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
注意:我已使用title属性(使用friendly_id gem)换出了文章和页面的ID。文章也是两种语言(因此我检查两个slu)
有什么想法吗?我已经尝试了其中的一些;
但到目前为止他们并没有完全做到这一点。谢谢:)♥
答案 0 :(得分:0)
我改进了解决方案,但它仍然没有感觉到100%的轨道效应。但是,这就是我要做的事情;
注意:我已使用title属性(使用friendly_id gem)换出了文章和页面的ID。文章也是两种语言(因此我检查两个slu)
Routing.rb (修改自blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app
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"
<强>最终强>