简体   繁体   中英

Ruby on Rails - passing parameters in link_to with if conditions?

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

  • If company=heise is set I want to display them in the URL and I furthermore want to not display it when it's not set.

Hope I made my question clear enough

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) %>

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) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM