Reputation: 284
I want to pass a parameter (for example the param is called company=heise) on a link to, but only if the param really is present.
Lets say:
I visit somesite.com
and click a link that would redirect me to mysite.com/?company=heise
On mysite
i have a few link_to's and I want them to pass the parameter company=heise
when it's present and since it is present now because I entered the site via mysite.com/?company=heise
it should do the following:
<%= link_to "This is a link", this_link_path, class: tl(this_link_path) %>
should redirect me to mysite.com/this_link/?company=heise
Hope I made my question clear enough
Upvotes: 2
Views: 1546
Reputation: 3412
The idea here is to create a helper method to manage the params that you want to send to this link conditionally.
# some_helper.rb
def carried_over_params(params = {})
interesting_keys = %i(company)
params.slice(*interesting_keys).compact
end
Afterwards, you should use this in the view
<%= link_to "This is a link", this_link_path(carried_over_params(params).merge(test: 'value')), class: tl(this_link_path) %>
Upvotes: 0
Reputation: 1407
Conditionally pass a hash, containing additional params for this_link_path
url helper.
<%= link_to "This is a link", this_link_path( ({company: params[:company] } if params[:company]) ), class: tl(this_link_path) %>
To be more concise you can compact the hash.
<%= link_to "This is a link", this_link_path({company: params[:company]}.compact), class: tl(this_link_path) %>
If you know that you'll need it more often, wrap this_link_path
call in a custom helper. Hash can contain additional params, including ones with fixed values.
def this_link_with_additional_params_path
this_link_path({company: params[:company], name: 'test'}.compact)
end
Then in view you can use:
<%= link_to "This is a link", this_link_with_additional_params_path, class: tl(this_link_path) %>
Upvotes: 3