2011-01-27 92 views
1

我想添加文章的標題到它的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. 

備註:

  1. 目前以下途徑很好地工作:/article/:id/:action/article/:id/:title有一個條件,文章不能有標題edit, show, index, etc.
  2. 我相信friendly_id是不必要在這裏,因爲路線包含:id明確。
  3. 依我之見,SO使用不同的路線問題/question/:id/:title/posts/:id/:action併爲用戶/users/:id/:name/users/:action/:id

回答

1

只需在模型中覆蓋to_param即可。從內存中未測試的例子:

def to_param 
    self.id + "-" + self.name.parameterize 
end 

這種方法意味着你沒有更改路由器,也可以繼續使用Model.find(params[:id])或相似。

基本上Railscast在另一個答案中提到了什麼,以及friendly_id的核心。

1

瑞安貝茨使用模型的名稱或任何其他屬性做了出色的screencast,在URL中,而不是ID。