2009-09-23 33 views
0

我正在使用机械化并在一个窗体上出现问题...窗体有两个同名的选择框。机械化设置重复名称的字段

如何选择第二个?

即。 NumNights第二次出现。

我的文档这样的发现:

form.set_fields(:foo => ['bar', 1]) 

但这丝毫不起作用:

form.field_with(:name => [ 'NumNights', 2 ]).options[no_days.to_i-1].select 

回答

2

得到一个窗体的引用,并迭代成员。事情是这样的:

my_fields = form.fields.select {|f| f.name == "whatever"} 
my_fields[1].whatever = "value" 

大功告成在填写表格后,提交。我没有运行这个代码,但我认为它应该工作。

+0

工作很好,谢谢! – holden 2009-09-23 12:59:14

+0

不客气! – Geo 2009-09-23 13:01:32

0

地理位置有一个体面的解决方案,但有几个错过的机会。

如果您只找到一个元素,那么使用Enumerable#find代替Enumerable#select然后再Array#first可能更有效。或者,您可以在选择期间简单地进行重新分配。

如果你看一下建议的方法有一个机会,你会触发一个异常,如果与该名称的字段没有找到:

# Original approach 
my_fields = form.fields.select {|f| f.name == "whatever"} 
# Chance of exception here, calling nil#whatever= 
my_fields[1].whatever = "value" 

我提倡使用可枚举#选择,只是做的工作内循环,更安全这样:

my_fields = form.fields.select do |f| 
    if (f.name == "whatever") 
    # Will only ever trigger if an element is found, 
    # also works if more than one field has same name. 
    f.whatever = 'value' 
    end 
end 

另一种方法是使用可枚举#找到返回至多有一个元素:

# Finds only a single element 
whatever_field = form.fields.find { |f| f.name == "whatever" } 
whatever_field and whatever_field.whatever = 'value' 

当然,你总是可以用异常捕获来哄骗你的代码,但这似乎适得其反。