轨道中Params对象中的变量符号

8 ruby-on-rails dynamic-data params

我有以下代码:

@profile.update_attributes(params[:xxxx_profile])
Run Code Online (Sandbox Code Playgroud)

其中xxxx代表男性或女性.基本上,表单提交传递一组female_profile[foo]或一组male_profile[foo],我想相应地更改它.假设我有一个可以插入的字符串代替xxxx,我该如何动态创建这个符号?

谢谢.

小智 12

尝试类似的东西:

@profile.update_attributes(params["#{gender}_profile".to_sym])
Run Code Online (Sandbox Code Playgroud)

或者,你应该能够传入字符串而不转换为符号,因为Rails使用了一个HashWithIndifferentAcceess for params:http://api.rubyonrails.org/classes/HashWithIndifferentAccess.html

@profile.update_attributes(params["#{gender}_profile"])
Run Code Online (Sandbox Code Playgroud)