Ruby-on-rails link_to 将参数与 url 一起发送并在目标页面上抓取它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2124862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
link_to send parameters along with the url and grab them on target page
提问by Omnipresent
How can i have a link on a page that takes the user to another URL and passes along a parameter and on the target url how can we pick up that parameter.
我如何在页面上建立一个链接,将用户带到另一个 URL 并传递一个参数,我们如何在目标 url 上获取该参数。
usually I add links like following:
通常我会添加如下链接:
<%= link_to "Add Product", '/pages/product' %>
But how can I send parameters along with this url? Can I pick them in the target action by using params[:parm_name]
但是如何将参数与此 url 一起发送?我可以在目标动作中选择它们吗using params[:parm_name]
回答by MBO
Just add them to link:
只需将它们添加到链接:
<%= link_to "Add Product", '/pages/product?param1=value1¶m2=value2' %>
and in controller:
并在控制器中:
param1 = params[:param1] # "value1"
param2 = params[:param2] # "value2"
If you use helper methods for routes (for example company_path), then you can add hash of params, so this two should be similar:
如果您对路由使用辅助方法(例如company_path),那么您可以添加参数的哈希值,因此这两个应该是相似的:
<%= link_to "Add Product", new_product_path(:param1 => "value1", :param2 => "value2") %>
<%= link_to "Add Product", "/products/new?param1=value1¶m2=value2" %>
From documentation:
从文档:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
# => <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
# => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
# => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
回答by dmcycloid
Here's a more rails-y way of doing it.
这是一种更简单的方法。
<%= link_to 'Link Text',
{controller: 'controller/name', action: 'action_name', query: params[:query]},
method: 'get',
:class=>'link_styling' %>
You need to reference your params in the hash defining the link. It also needs to be a GET method. Styling is optional of course.
您需要在定义链接的哈希中引用您的参数。它也需要是一个 GET 方法。样式当然是可选的。
This should really be here too: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
这也应该在这里:http: //api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

