如何重构一个简单的动态属性?
我有一个表单可以处理同一表单的四种不同类型的方面。在我的 SQL 列中,我有四个不同的属性。
其中只有一个会有数据。
Distribution =>
zip_code: nil
me_topic: nil
sex: nil
age: nil
为了区分它们,我想设置一个 case 语句,并向 create 调用添加一个 dynamic 属性:
@type = case params[:type]
when "zip" then ":zip_code"
when "interest" then ":me_topic"
when "sex" then ":sex"
when "age" then ":age"
end
@cur_item = Distribution.new(@type => params[:value])
# Unfortunately, this is not the proper way to create a dynamic attribute
@distribution = @email.distributions.create(params[:distributions])
完成此语句的正确语法是什么?
I have a form that handles four different types of facets of the same form. In my SQL column, I have the four different attributes.
Only one of them is going to have data in it.
Distribution =>
zip_code: nil
me_topic: nil
sex: nil
age: nil
In order to differentiate between them, I wanted to set up a case statement, and add a dynamic attribute to the create call :
@type = case params[:type]
when "zip" then ":zip_code"
when "interest" then ":me_topic"
when "sex" then ":sex"
when "age" then ":age"
end
@cur_item = Distribution.new(@type => params[:value])
# Unfortunately, this is not the proper way to create a dynamic attribute
@distribution = @email.distributions.create(params[:distributions])
What is the proper syntax for completing this statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
声明一个名为
type_map
的方法现在您可以按如下方式使用地图:
Declare a method called
type_map
Now you can use the map as follows:
这就是我的想法,但请随意最好地回答我的问题。
This is what I went with, but feel free to best my answer.
好吧,改进代码(您在答案中发布的内容)的一种方法是排除重复的 params[:value] ,如下所示:
Well, one way to improve your code (what you posted in your answer) would be to factor out the repeated
params[:value]
as follows: