假设路线

map.resources :articles

你怎么得到这个

/articles?most_popular

使用 link_to 方法?

尝试了以下内容:

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

注意:我正在使用 has_scope

inherited_resources >
有帮助吗?

解决方案

如果您没有为参数添加值,则不会遵守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标准,您的网址看起来几乎相同(更改一个?一个/),您的控制器将被简化(您将从索引中分离出最常用的操作)。

问候!

更新(2017):似乎W3C标准没有强制要求 field = value 语法(或者不再强制要求它)。然而,一些服务器被记录为“阻塞”。对不符合此语法的查询。请参阅 url查询参数是否有效(如果有)没有价值?了解详情。

其他提示

你拥有的最后一个例子:

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

是正确的方法。否则你可以手工构建链接:

<a href="<%= articles_path %>?most_popular">articles</a>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top