仅当条件为真时才将选项传递给方法。优雅的?
我有一个部分,根据模型的属性类型在我的表单中插入适当的输入。我传递一个属性名称数组,我的部分放置一个 form.text_field,其中属性是字符串,当属性是整数时放置 form.select (我还有一种方法来查找与属性关联的文本值的集合)等等日期时间等等。
问题是部分需要尽可能通用,所以我想检查是否有 params[:search][:attr_name] 来设置默认值,如果没有,我使用默认值调用,设置表单中模型的值。
当然,我可以做这样的事情(我使用 HAML):
- if search_param(field)
= form.text_field field, :value => search_param(field)
- else
= form.text_field field
但它真的很难看。仅当条件为真时,才有任何方法可以将选项传递给方法。像这样的东西。
= form.text_field field, (:value => search_param(field) ) if search_param(field)
我也尝试这样做:
= form.text_field field, :value => search_param(field) || field.to_sym
但它在输入
创意中显示“字段”?
I have a partial that inserts in my forms the appropriate input according to the model's attribute type. I pass an array of attribute names and my partial puts a form.text_field where the attribute is a string, a form.select when the attribute is an integer (I also have a way to find the collection of text values associated to a attribute) and so on with datetime, ect.
The problem is that partial need to be as generic as possible, so I want to check if I have a params[:search][:attr_name] to set the default value, and if a don't have it, I use the default call, that sets the value of the model in the form.
Of course, i can do somethig like this (I use HAML) works:
- if search_param(field)
= form.text_field field, :value => search_param(field)
- else
= form.text_field field
but it's really ugly. There is any way to pass an option to a method only if a condition is true. Something like this.
= form.text_field field, (:value => search_param(field) ) if search_param(field)
I tried also to do:
= form.text_field field, :value => search_param(field) || field.to_sym
but it shows "field" inside the input
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定这是否是您想要的结果,但是如果您使用 model.send(field) 代替 field.to_sym 从模型中获取属性值会怎样?所以它会是这样的:
I'm not sure if this is the result you want, but what if you instead of field.to_sym use model.send(field) to get the attribute value from the model? So it would be something like this:
这是使用三元运算符的一种方法:
Here's one way to do it, using the trinary operator: