Rails Unable to convert unpermitted parameters to hash

会有一股神秘感。 提交于 2019-11-29 05:28:09

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 you could use request.parameters.merge(...) (as mentioned in this answer) or params.to_unsafe_h.merge(...). Both of these basically circumvent the strong-parameters protection when creating the link. By default, that means that any parameters that were in the original request would also appear in the link URL. I would guess that isn't too risky in this particular situation, but if you have code elsewhere that doesn't sanitize the parameters properly, this could make that situation a little worse.

You can use this hack:

params.to_enum.to_h

I think rails developers will restrict it when they know it's the way to use unpermitted parameters. :)

you can try to use request.parameters.merge, below is sample for your code above

<%= link_to title, listings_path(request.parameters.merge({:sort => "column", :direction => "direction", :page => nil})), :class => "form-control css_class" %>  

I believe if you pass column to permit it should get you working again!

def sortable(column, title = nil)
    title ||= column.titleize
    css_class = column == sort_column ? "current #{sort_direction}" : nil
    direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
    link_to title, params.permit(column).merge(sort: column, direction: direction, page: nil), { class: css_class }
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!