8

我有以下代码:

@profile.update_attributes(params[:xxxx_profile])

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

谢谢。

4

3 回答 3

12

尝试类似:

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

或者,您应该能够在不转换为符号的情况下传递字符串,因为 Rails 使用 HashWithIndifferentAcceess 作为参数: http ://api.rubyonrails.org/classes/HashWithIndifferentAccess.html

@profile.update_attributes(params["#{gender}_profile"])
于 2009-12-08T03:13:24.347 回答
3

弄清楚了。认为它可能对某人有用。

@profile.update_attributes(params[(@sexstring + "_profile").to_sym])
于 2009-12-08T03:12:40.343 回答
1

你也可以做

@profile.update_attributes(params[:"#{gender}_profile"])
于 2009-12-08T03:17:54.763 回答