2012-05-12 75 views
2

我以爲我知道如何重寫路徑助手,但我沒有得到我預期的行爲。自定義路徑生成器

我嘗試添加這樣的事情我ApplicationHelper:

def post_path(post) 
    "/posts/#{post.id}/#{post.url}" 
end 

但出於某種原因,在我的控制器之一,當我嘗試使用post_path(@post)它只是返回完整的URL,像/posts/4faddb375d9a1e045e000068/asdf(這是瀏覽器中的當前網址)而不是/posts/4faddb375d9a1e045e000068/post-title-here

在我的路線文件:

get '/posts/:id/:slug' => 'posts#show', :as => 'post'

奇怪的是,如果我用post_path(@post, @post.url),它工作正常。如果在視圖中我使用post_path(@post)它可以正常工作。 (@post.url返回URL友好標題)

如果你看不出來,我想最終得到類似計算器的網址包含的ID和料塊在最後的行爲,如果沒有按蛞蝓」 t使用給定的id匹配模型,它將重定向到正確的url。

+0

你在哪裏定義'post.url'? –

+0

post.url是模型上的一種方法,並以url友好的方式返回帖子的標題。 – Matthew

回答

0

我想嘗試將整個def post_pathapplication_controller.rb並使其幫助helper_method :post_path。你會得到兩全其美的。

+0

看到一個將路徑直接注入到'Rails.application.routes.url_helpers' – bbozo