2010-01-08 55 views
6

我有一個博客資源blogs_controller,所以我如下得到了典型的路線現在:在Rails中做「/ blogs /:year /:month /:day /:permalink」路線的最佳方法是什麼?

/blogs/new 
/blogs/1 
/blogs/1/edit #etc 

但在這裏就是我想:

/blogs/new 
/blogs/2010/01/08/1-to_param-or-something 
/blogs/2010/01/08/1-to_param-or-something/edit #etc 
... 
/blogs/2010/01 # all posts for January 2010, but how to specify custom action? 

我知道我可以通過map.resources和map.connect的組合來實現,但是我有很多通過「new_blog_path」鏈接到其他頁面的視圖,我不想去編輯它們。單獨使用map.resources可能嗎?這可能並不容易,但我並不反對聰明。我想的是一樣的東西:

map.resources :blogs, :path_prefix => ':year/:month/:day', :requirements => {:year => /\d{4}/, :month => /\d{1,2}/, :day => /\d{1,2}/} 

但我不知道如何與像行動工作「新」或「創造」,而這也給了我像/2010/01/08/blogs/1-to_param-etc路線與博客中的中間URL。

那麼,有沒有一個聰明的解決方案,我錯過了,或者我需要去map.connect路線?

回答

13

我遇到同樣的問題,最近,和,雖然這可能不是你要找的內容,這是我做了什麼來照顧它:

的config/routes.rb中

map.entry_permalink 'blog/:year/:month/:day/:slug', 
        :controller => 'blog_entries', 
        :action  => 'show', 
        :year  => /(19|20)\d{2}/, 
        :month  => /[01]?\d/, 
        :day  => /[0-3]?\d/ 

blog_entries_controller.rb:

def show 
    @blog_entry = BlogEntry.find_by_permalink(params[:slug]) 
end 

blog_entries_helper.rb:

def entry_permalink(e) 
    d = e.created_at 
    entry_permalink_path :year => d.year, :month => d.month, :day => d.day, :slug => e.permalink 
end 

_entry.html.erb:

<h2><%= link_to(entry.title, entry_permalink(entry)) %></h2> 

和完整的緣故:

blog_entry.rb:

before_save :create_permalink 

#... 

private 

def create_permalink 
    self.permalink = title.to_url 
end 

#to_url方法來自rsl的Stringex

我自己對Rails(和編程)還是一個新手,但這可能是最簡單的方法。這不是一種REST式的處理事情的方式,因此不幸的是,您無法從map.resources中獲益。

我不確定(因爲我沒有嘗試過),但是您可能可以在application_helper.rb中創建適當的幫助程序來覆蓋blog_path等的默認路由幫助程序。如果這有效,那麼你將不必更改任何視圖代碼。

如果你覺得喜歡冒險,可以試試Routing Filter。我考慮過使用它,但對於這項任務似乎過度。

另外,如果你不知道,兩件事情可以做,以從腳本/控制檯中測試你的路由/路徑:

rs = ActionController::Routing::Routes 
rs.recognize_path '/blog/2010/1/10/entry-title' 

app.blog_entry_path(@entry) 

祝你好運!

+0

感謝周杰倫這是一個很好的寫法,爲我節省了很多時間! – 2010-07-10 20:00:08

+0

真棒解釋! – 2010-10-19 03:42:48

+0

該路線的導軌3版本是什麼? – sguha 2013-03-15 11:10:04

2

API Docs

map.connect 'articles/:year/:month/:day', 
      :controller => 'articles', 
      :action  => 'find_by_date', 
      :year  => /\d{4}/, 
      :month  => /\d{1,2}/, 
      :day  => /\d{1,2}/ 

使用上面的路線,該URL 「本地主機:3000 /用品/ 2005/11/06」 映射到

params = { :year => '2005', :month => '11', :day => '06' } 

看起來你想做的事同樣的事情,但後綴slu suff。您的新鏈接和編輯鏈接仍然是「舊學校」鏈接,如「localhost:3000/articles/1/edit」和「localhost:3000/articles/new」。只是「顯示」鏈接應該用這個更新。

+0

嘿jarrett,感謝您的職位。 slu is是沒有問題的,to_param可以照顧到這一點。我真正想做的是擺脫'map.connect',並在'map.resources'的調用中處理這個,所以我不需要修改我現有的所有對blog_path(@blog)的調用等。理想情況下我想打電話給url_for(@blog),然後找回類似'/ blogs/2010/01/08/1-to_param-or-something'的東西,我想這是map.connect所不可能的。我猜我想要的是不可能的(無論如何,這種URL格式RESTful?),我只是想看看是否有人有任何創造性的解決方案。 – carpeliam 2010-01-08 22:34:02

相關問題