gpt4 book ai didi

ruby-on-rails - rails : Specifing params without value to link_to

转载 作者:行者123 更新时间:2023-12-04 03:19:08 25 4
gpt4 key购买 nike

假设路线

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

注意:我正在使用 inherited_resourceshas_scope

最佳答案

如果您不向参数添加值,您将不会遵守 W3C 标准,该标准规定 params 部分的格式为 field=value .

我建议您改为向您的文章 Controller 添加一个新的 :most_popular 操作。

在你的 routes.rb 上:

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

在您的 Controller 上:
class ArticlesController < ApplicationController
...
def most_popular
@articles = ...
end

关于你的看法:
link_to most_popular_articles_path() # /articles/most_popular

这将是 HTML 兼容的,您的 url 看起来几乎相同(改变一个?一个/)并且您的 Controller 将被简化(您将 most_popular 操作与索引分开)。

问候!

更新(2017 年):W3C 标准似乎没有强制要求 field=value语法(或不再强制要求)。然而,一些服务器被记录为“阻塞”不符合此语法的查询。见 Is a url query parameter valid if it has no value?详情。

关于ruby-on-rails - rails : Specifing params without value to link_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com