ruby-on-railsrubyruby-on-rails-5

Rails link_to and merge parameter into existing parameters


I have a link_to directive that adds a link to an icon by passing a block to link_to. What I'm trying to do is merge existing query parameters in the URL and append this one as well if it is clicked. Syntax seems broken:

<%= link_to {params:params.merge({foo: bar })}, title: 'Title of my icon' do %>
   <i class="myicon"></i>
<% end %>

what's the correct way to write the link_to above to merge my foo query parameter into the existing query parameters in the URL?


Solution

  • url_for can be used to generate a URL from an extended params hash:

    <%= link_to url_for(params.merge(foo: bar)), title: 'Title of my icon' do %>
      <i class="myicon"></i>
    <% end %>