Rails: Specifing params without value to link_to

痞子三分冷 提交于 2020-01-30 06:35:08

问题


Supposing the route

map.resources :articles

how do you get this

/articles?most_popular

using link_to method?

tried the following:

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

note: i'm using inherited_resources with has_scope


回答1:


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.

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

On your routes.rb:

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

On your controller:

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

On your views:

link_to most_popular_articles_path() # /articles/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).

Regards!

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.




回答2:


The last example you have:

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

Is the correct way. Otherwise you could just construct the link by hand:

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


来源:https://stackoverflow.com/questions/1816030/rails-specifing-params-without-value-to-link-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!