2011-09-21 20 views
2

我試圖設置rails以同時使用路由中博客文章的ID和句柄(它只是標題的URL安全版本)。在Rails中使用id和句柄進行路由

match '/articles/:id/:handle', :to => 'articles#show' 
resources :articles 

這個工作,當然 - 但我似乎不能成立to_param方法模型OS較長的URL - 與手柄連接,是默認的。

這不起作用(不,我真的它預計):

def to_param 
    "#{id}/#{handle}" 
    end 

我得到一個No route matches {:action=>"edit", :controller=>"articles",錯誤。我也嘗試過使用句柄,但是接下來Rails會使用句柄而不是ID生成到資源的鏈接。我知道我可以用 - 代替/,但我更喜歡/。任何方式使這項工作?如果我不得不在我的link_to助手中添加一些額外的參數,那沒問題。

+0

我可能會在這裏留下痕跡。你如何產生你的鏈接? –

回答

2

您是否嘗試過Hashlink_to

link_to "Link", {:id => @article.id, :handle => @article.handle} 

更新

您必須修改您的路線:

match '/articles/:id/:handle', :to => 'articles#show', :as => :article_with_handle 

,並使用以下助手生成的鏈接:

link_to "Link", article_with_handle_path(:id => @article.id, :handle => @article.handle) 

可以覆蓋幫手以簡化事情:

def article_with_handle_path(article) 
    super(:id => article.id, :handle => article.handle) 
end 

,並使用它像這樣:

link_to "Link", article_with_handle_path(@article) 
+0

是的,它只是用查詢字符串創建URL。 – Slick23

+0

這導致我重複我的問題:你如何產生你的鏈接? –

+0

這引出我的意思,就像你上面展示的一樣。你問我是否嘗試過。我說,是的 - 它不起作用。 – Slick23

1

好了,這就是我所做的,從上面的答案刪除查詢字符串的問題:

改變了路線,以這樣的:

match '/articles/:id/:handle' => 'articles#show', :as => :handle 

從模型中刪除to_param方法,然後生成如下鏈接:

link_to 'Show', handle_path(:handle => article.handle, :id => article.id) %> 

這是有效的,但顯然可以用上面的幫助器濃縮。只需將其中一行改爲:args[1] = handle_path(:id => args[1].id, :handle => args[1].handle)