简体   繁体   English

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

[英]Variable symbol in Params object in rails

I have the following code: 我有以下代码:

@profile.update_attributes(params[:xxxx_profile])

where xxxx stands for either male or female. 其中xxxx代表男性或女性。 Basically the form submit passes either a set of female_profile[foo] or a male_profile[foo] and i want to change it accordingly. 基本上表单提交传递一组female_profile[foo]male_profile[foo] ,我想相应地更改它。 Assuming I have a string that can be inserted in lieu of xxxx, how do I dynamically create this symbol? 假设我有一个可以插入的字符串代替xxxx,我该如何动态创建这个符号?

Thanks. 谢谢。

Try something like: 尝试类似的东西:

@profile.update_attributes(params["#{gender}_profile".to_sym])

or, you should be able to pass in the string without converting to a symbol, because Rails uses a HashWithIndifferentAcceess for params: http://api.rubyonrails.org/classes/HashWithIndifferentAccess.html 或者,你应该能够传入字符串而不转换为符号,因为Rails使用了一个HashWithIndifferentAcceess for params: http ://api.rubyonrails.org/classes/HashWithIndifferentAccess.html

@profile.update_attributes(params["#{gender}_profile"])

Figured it out. 弄清楚了。 Thought it might be useful for someone. 认为它可能对某人有用。

@profile.update_attributes(params[(@sexstring + "_profile").to_sym])

你也可以这样做

@profile.update_attributes(params[:"#{gender}_profile"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM