我想添加文章的標題到它的URL類似於SO URLs。我建議使用在answer以下安裝到我的另一個問題減少Rails路由和url助手的冗餘
# routes.rb
match '/articles/:id/:title' => 'articles#show', :as => :article_with_title
# articles/index.html.erb
link_to article.title, article_with_title_path(article, :title => article.title.downcase.gsub(/[^a-z0-9]+/,' ').strip.gsub(/\s+/,'-'))
它的工作原理,但我覺得有點多餘。有沒有辦法讓它更好?那麼處理多條路線的另一種通用方法呢?
match '/articles/:id/:title' => 'articles#show'
match '/users/:id/:name' => 'users#show'
etc.
備註:
- 目前以下途徑很好地工作:
/article/:id/:action
,/article/:id/:title
有一個條件,文章不能有標題edit, show, index, etc.
- 我相信
friendly_id
是不必要在這裏,因爲路線包含:id
明確。 - 依我之見,SO使用不同的路線問題
/question/:id/:title
,/posts/:id/:action
併爲用戶/users/:id/:name
,/users/:action/:id