当选项为nil rails 4时,如何隐藏表单选择选项

时间:2022-08-24 10:25:26

I've got the following form select:

我有以下表格选择:

<%= f.select(:size_requested, [@item.size1, @item.size2, @item.size3, @item.size4, @item.size5, @item.size6, @item.size7, @item.size8, @item.size9, @item.size10], {}, { class: 'form-control quantity-select' }) %>

I'm trying to have it where only the sizes that are not nil are presented as options and avoid this:

我试图让它只有非零的大小作为选项出现,并避免这种情况:

当选项为nil rails 4时,如何隐藏表单选择选项

When I try things like (@item.size6 if @item.size6) for the options I still have the same issue and the nil options are still visible. Can anyone lead me in the right direction to solve this in a clean way?

当我尝试类似(@ item.size6 if @ item.size6)的选项时,我仍然遇到同样的问题,并且仍然可以看到nil选项。谁能引导我朝着正确的方向以干净的方式解决这个问题?

Thanks for your help!

谢谢你的帮助!

1 个解决方案

#1


You can use the compact method to remove nils from an array. For example:

您可以使用compact方法从数组中删除nils。例如:

[1, nil, 2, nil].compact

Also, as a comment on your question suggests, it's a good idea to set up the array in your controller and then reference that in the view rather than performing logic in the view itself.

另外,正如您对问题的评论所示,最好在控制器中设置数组,然后在视图中引用该数组,而不是在视图本身中执行逻辑。

#1


You can use the compact method to remove nils from an array. For example:

您可以使用compact方法从数组中删除nils。例如:

[1, nil, 2, nil].compact

Also, as a comment on your question suggests, it's a good idea to set up the array in your controller and then reference that in the view rather than performing logic in the view itself.

另外,正如您对问题的评论所示,最好在控制器中设置数组,然后在视图中引用该数组,而不是在视图本身中执行逻辑。