2009-11-29 37 views
2

假設使用link_to方法途徑的Rails:Specifing PARAMS沒有價值LINK_TO

map.resources :articles 

你是怎麼得到這個

/articles?most_popular 

嘗試了以下內容:

link_to articles_path(:most_popular) # exception 
link_to articles_path(:most_popular => nil) # /articles 
link_to articles_path(:most_popular => true) # /articles?most_popular=true 

注:我使用inherited_resourceshas_scope

回答

3

如果沒有一個值添加到你會不會尊重W3C標準,規定任的PARAMS部分的形式field=value的參數。

我建議您將新的:most_popular動作添加到您的文章控制器中。

在你的routes.rb:

map.resources :articles, :collection => {:most_popular=>:get} 

在您的控制器:

class ArticlesController < ApplicationController 
... 
def most_popular 
    @articles = ... 
end 

在您的觀點:

link_to most_popular_articles_path() # /articles/most_popular 

這將是兼容HTML,您的網址就會看實際上是一樣的(改變一個?),你的控制器將被簡化(你將會把most_popular動作分開d來自索引)。

問候!

更新(2017):似乎W3C標準沒有強制要求field=value語法(或不再強制它)。但是,有些服務器被記錄爲在不符合此語法的查詢中「窒息」。詳情請參閱Is a url query parameter valid if it has no value?

+0

我的代碼完全是這樣的。然而,最近我開始重構我的代碼,並想知道如何使用RESTFUL和/或重新構建它。是不是「最受歡迎」而不是索引過濾器,而是查詢選項(filter = most_popular) – gorn 2013-11-18 21:12:39

+1

Restful並不意味着僅限於CRUD。這意味着每個網址都可以作爲資源。問題是:最受歡迎的文章與普通文章有什麼不同,應該擁有自己的資源?答案不是「我必須有CRUD」。這是「這取決於應用程序」。如果它們不是非常重要,那麼添加一個過濾器參數就足夠了。如果他們超級重要,他們應該得到他們自己的控制者,可能。我的解決方案是中級。 – kikito 2013-11-21 10:20:05

+0

是的,這很堅強。謝謝gorn – gorn 2014-04-12 17:48:54

1

你的最後一個例子:

link_to articles_path(:most_popular => true) # /articles?most_popular=true 

纔是正確之路。否則,你可能只是建立鏈接的手:

<a href="<%= articles_path %>?most_popular">articles</a>