Search code examples
ruby-on-railsruby-on-rails-5strong-parameters

Rails 5: Merging parameters in view - where to permit them?


what is the new way in Rails 5 to merge actual page query strings to link with a new one?

Let's assume I have page http://localhost:3000?type=a and I want to add another query param to the link on page:

<%= link_to root_path(params.merge(tech: "b")) do %>

but I get: unable to convert unpermitted parameters to hash. Where I should permit the params?
I tried to do it in before_action filter, but it seems to be too late.

Thanks

EDIT:

My controller:

class HomeController < ApplicationController
  before_action :permit_params

  ...

  private

  def permit_params
    params.permit(:tech, :type)
  end
end

Solution

  • You just need to whitelist the params you want to merge with

    <%= link_to 'Home', root_path(params.permit(:type, :tech).merge(tech: 'b')) %>
    

    and get /?tech=b&type=a. If you really want all parameters, you can use permit!

    <% params.permit! %>
    <%= link_to 'Home', root_path(params.merge(tech: 'b')) %>
    

    which will give you /?action=index&controller=home&tech=b&type=a, which while those keys don't seem to be messing anything up, is very likely not desired (and controller and action will be overridden and not passed into your controller action). NOTE: The controller/action are set that way because I'm on my HomeController index action, not because that's what root_path is pointing to

    I just don't think I can recommend doing this, however (seems iffy, imo)...stick with whitelisting.