2013-03-25 20 views
0

我想有網址與參數化重寫,因爲在這裏說明一下:How do I rewrite URL's based on title?錯誤的URL與參數化

這裏是我的模型:

class Article < ActiveRecord::Base 
    belongs_to :category 

    self.per_page = 5 

    def to_param 
    "#{title.parameterize}" 
    end 
end 

而且我的鏈接:

<%= link_to(article.title, blog_article_path(article), {:class => "blog_title"}) %> 

問題是,我沒有像/blog/article/"my-article-title"一個鏈接,但我有/blog/article."my-article-title",這是錯誤的,而不是解釋。

你知道原因嗎?

我route.rb:

get "blog/index" 
get "blog/category" 
get "blog/article" (I don't use the show action of my article controller, is it the reason ?) 

resources :categories 

resources :articles 

感謝

+0

難道您發佈'routes.rb'文件的相關部分? – Bitterzoet 2013-03-25 14:07:51

+0

最初的帖子已更新 – eluus 2013-03-25 14:14:05

回答

0

使用link_to你是通過傳遞資源的方式只有真正的作品當你真正在你的路線文件中使用的資源。

這是使用非足智多謀的路線和一個由資源所產生的差異(耙路輸出):

blog_article GET /blog/article(.:format) 

article GET /articles/:id(.:format) 

當您使用article_path(@article)它會在:id填補與資源的ID。

我建議你使用的物品控制器的表演動作,所以你必須/blog/articles/:id或者你可以做這樣的事情,如果你真的想要的路由:

get "blog/article/:id" => "articles#show", :as => 'blog_article' 

它變成:

blog_article GET /blog/article/:id(.:format) 

official guides有一些這方面的好消息。

+0

這是因爲find始終會通過它的ID列來搜索記錄。本質上它只是''my-article-title「.to_i',在這種情況下它的計算結果爲0。有2個選項,使用「#{id} -title.parameterize」,因此它會生成像/ articles/1-my-title這樣的URL(當執行.to_i時它會查找記錄ID 1),或者使用另一列來查找文章。我建議看看這個railscast:http://railscasts.com/episodes/63-model-name-in-url-revised – Bitterzoet 2013-03-25 15:15:07