简体   繁体   中英

url_helper error when merging in required parameter

I am trying to merge a value to the params hash, and pass the resulting hash to a url helper. (Using Rails 5)

For example. I have the following routes

routes.rb

get 'test-url/:arg_1' => 'test#test_action_1', :as => 'test_test_action_one'
get 'test-url/:arg_1/:arg_2' => 'test#test_action_2', :as => 'test_test_action_two'

The user visits /test-url/value-1 , and I want to generate a link in the view to /test-url/value-1/value-2

in view file

link_to test_test_action_two_url(params.permit(:arg_1).merge(arg_2: 'value-2'))

I get the following error:

No route matches {:action=>"test_action_2", :arg_1=>"value-1", "arg_1"=>"value-1", "arg_2"=>"value-2", :controller=>"test"} missing required keys: [:arg_2]

Under the hood the ActionController::Parameters object is maintaining an internal hash (with_indifferent_access). After the merge , the hash still has indifferent_access and you can access arg_2 using a symbol or string.

However, I'm not sure why the url generator is unable to find the :arg_2 key...

ActionController::Parameters uses HashWithIndifferentAccess which stores keys as string instead of symbols. But routing URL helpers requires the arguments to be in symbol keys. So as it is mentioned in the error, arg_2 needs to be in symbol key.

Why does Rails' `HashWithIndifferentAccess` store keys as strings and not symbols?

Try creating a new normal Hash:

test_test_action_two_path({arg_1: "value_1", arg_2: "value_2"})

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