Rails:将没有值的参数指定给 link_to [英] Rails: Specifing params without value to link_to

查看:49
本文介绍了Rails:将没有值的参数指定给 link_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设路线

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

note: i'm using inherited_resources with has_scope

推荐答案

如果您不向参数添加值,您将不会遵守 W3C 标准,该标准要求 params 部分具有表单 field=值.

If you don't add a value to the parameters you will not be respecting the W3C standard, which mandates that the params section has the form field=value.

我建议您改为向文章控制器添加一个新的 :most_popular 操作.

I recommend that you add a new :most_popular action to your articles controller instead.

在你的 routes.rb 上:

On your 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 兼容的,您的 url 看起来几乎相同(改变一个?一个/),并且您的控制器将被简化(您将把 most_popular 操作与索引分开).

This will be HTML-compliant, your urls will look practically the same (changing one ? by one /) and your controller will be simplified (you will have the most_popular action separated from the index).

问候!

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

Update (2017): It appears that the W3C standard doesn't mandate the field=value syntax (or doesn't mandate it any more). However some servers are documented to "choke" on queries not complying with this syntax. See Is a url query parameter valid if it has no value? for details.

这篇关于Rails:将没有值的参数指定给 link_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆