仅当条件为真时才将选项传递给方法。优雅的?

发布于 2024-10-03 01:42:37 字数 714 浏览 0 评论 0原文

我有一个部分,根据模型的属性类型在我的表单中插入适当的输入。我传递一个属性名称数组,我的部分放置一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫轩蝶泪 2024-10-10 01:42:37

我不确定这是否是您想要的结果,但是如果您使用 model.send(field) 代替 field.to_sym 从模型中获取属性值会怎样?所以它会是这样的:

= form.text_field field, :value => ( search_param(field) || model.send(field) )

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:

= form.text_field field, :value => ( search_param(field) || model.send(field) )
猫烠⑼条掵仅有一顆心 2024-10-10 01:42:37

这是使用三元运算符的一种方法:

form.text_field *([field] + (search_param(field) ? [:value => search_param(field)] : []))

Here's one way to do it, using the trinary operator:

form.text_field *([field] + (search_param(field) ? [:value => search_param(field)] : []))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文