rails 3.0.10 条件 select()

rails 3.0.10 conditions in select()

我有这个select

<%= select("post", "field",@variable.all.collect) {|p| [ p.name, p.id ] }, :include_blank =>'blank')%>            

生成 4 个寄存器的下拉列表

我做到了

{|p| [ p.name, p.id ] if helper_method(p.id) }

期待这个输出:

blank
reg4

相反,我得到了这个输出:

blank



reg4

我不知道如何获得预期的输出

@variable.all.collect {|p| [ p.name, p.id ] if helper_method(p.id) } 将 return 类似于 [["blank", 1],nil,nil,nil,["reg4", 2]],因为每次不满足 helper_method(p.id) 条件时,它 returns nil 到收集。这为您提供了 nil 值的空白选项,因此一个简单的解决方案是使用 .compact

删除 nils
@variable.all.collect {|p| [ p.name, p.id ] if helper_method(p.id) }.compact

还有其他方法,您可以首先避免 returning nil 并在另一个传递中删除选项,如下所示:

@variable.all.collect {|p| [ p.name, p.id ] }.reject{|p| !helper_method(p1)}