【问题标题】:Mechanize setting a field with a duplicate name机械化设置字段重名
【发布时间】:2009-09-23 12:39:48
【问题描述】:

我正在使用 mechanize 并且在一个表单上遇到问题...该表单有两个同名的选择框。

如何选择第二个?

即。 NumNights 第二次出现。

我在文档中发现了这样的内容:

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

但这不起作用:

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

【问题讨论】:

    标签: ruby-on-rails ruby forms duplicates mechanize


    【解决方案1】:

    获取对表单的引用,并遍历成员。像这样:

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

    填写完表格后,提交。我没有运行此代码,但我认为它应该可以工作。

    【讨论】:

      【解决方案2】:

      Geo 有一个不错的解决方案,但也有一些错失的机会。

      如果您只查找一个元素,则使用 E​​numerable#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"
      

      我提倡使用 Enumerable#select 并简单地在循环内完成工作,这样更安全:

      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
      

      另一种方法是使用最多返回一个元素的 Enumerable#find:

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

      当然,您总是可以在代码中添加异常捕获,但这似乎适得其反。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多