Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]

like image 953
Omnipresent Avatar asked Jan 23 '10 21:01

Omnipresent


People also ask

How do I add URL parameters to URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

How do you pass parameters in Rails?

What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes. rb, you can use path helpers. And you need to control that account_id is allowed for 'mass assignment'.

What is get parameter in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.


1 Answers

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> 
like image 144
MBO Avatar answered Oct 13 '22 19:10

MBO