开发者

link_to send parameters along with the url and grab them on target page

开发者 https://www.devze.com 2022-12-17 17:57 出处:网络
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.

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.

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]


Just add them to link:

<%= link_to "Add Product", '/pages/product?param1=value1&param2=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:

<%= link_to "Add Product", new_product_path(:param1 => "value1", :param2 => "value2") %>
<%= link_to "Add Product", "/products/new?param1=value1&param2=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&amp;baz=quux">Nonsense search</a>


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.

This should really be here too: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

0

精彩评论

暂无评论...
验证码 换一张
取 消