Question

My current link

link_to title, params.merge(:sort => column, :direction => direction, :page => nil, :search => nil), {class: css_class}

I want to add remote: true into the mix but when I encapusulate it with the params.merge (i.e. {params.merge(), remote: true} I get a syntax error. In rails I need to encaps the url options and the html options separately right?

title and css_class are both variables inside the helper method this link is in

Was it helpful?

Solution

Better to use:

link_to 'title', params.merge(:sort => column, :direction => direction, :page => nil, :search => nil), {class: css_class}, :remote => true

OTHER TIPS

You can do it like this:

link_to title, params.merge(:sort => column, :direction => direction, :page => nil, :search => nil), class: css_class, remote: true

In Rails 5, ActionController::Parameters no longer inherits from Hash, in an attempt to discourage people from using Hash-related methods on the request parameters without explicitly filtering them.

As part of this pull request, which was backported into Rails 5.1 and partially into Rails 5.0, an exception is raised if you try to call to_h on the parameters object without calling permit.

Calling merge on the original params object (params.merge(:sort => column, :direction => direction, :page => nil)) returns a new ActionController::Parameters object with the same permitted status (that is, permit has not been called on it). The link_to method then ends up calling to_h on that object, which raises the exception.

If you know which parameters should be allowed in the link, you can call permit with those listed.

params.permit(:param_1, :param_2).merge(:sort => column, :direction => direction, :page => nil)
# OR
params.merge(:sort => column, :direction => direction, :page => nil).permit(:param_1, :param_2, :sort, :direction, :page)

If you don't know which parameters could be included in the link, then it's possible to call request.parameters.merge(...) (as mentioned in this answer) or params.to_unsafe_h.merge(...). However, as pointed out in comments, this is a security risk when the result is passed to link_to, as a parameter like host would be interpreted as the actual host for the link instead of a query parameter. There are several other keys that also have special meaning in link_to (everything accepted by url_for, plus :method), so it's generally a risky approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top