【问题标题】:Trouble setting up Rails custom form helper method设置 Rails 自定义表单帮助方法时遇到问题
【发布时间】:2016-01-15 17:39:08
【问题描述】:

我正在尝试创建自定义表单辅助方法(用于自定义 HTML 复选框标记),但遇到了一些问题。我创建了以下助手,wrapped_check_box

module FormHelper
  class ActionView::Helpers::FormBuilder
    include ActionView::Helpers::FormTagHelper
    include ActionView::Helpers::FormOptionsHelper

    def wrapped_check_box(name, options = {})
      raw "<div class='checkbox-wrapper'>" + \
        check_box_tag(@object_name, name, options) + \
        "<span class='checkbox-check'></span>" + \
      "</div>"
    end
  end
end

示例用法:

&lt;%= f.wrapped_check_box :receives_updates %&gt;

当我使用它时,在这个来自新 User 模型的示例中,我得到以下输出:

<div class="checkbox-wrapper">
  <input type="checkbox" name="user" id="user" value="receives_updates" checked="checked">
  <span class="checkbox-check"></span>
</div>

这里有两个问题:

  1. 即使我传入checked: false,也会自动检查该字段
  2. 这似乎是不正确的 id 值,它与 &lt;label&gt; 标记以及一般所有内容都混淆了

我一直在关注各种文章来拼凑这个,但显然我做错了什么。任何帮助表示赞赏:)

更新

我通过更新check_box_tag 方法取得了一些进展:

check_box_tag("#{@object_name}[#{name.to_s}]", 1, options)

现在输出:

<input type="checkbox" name="user[receives_updates]" id="user_receives_updates" value="1" checked="checked">

这正是我想要的,但不幸的是它仍然总是输出checked="checked",即使我将它作为假传递。

有什么想法吗?

【问题讨论】:

  • 你对id的期望值是多少
  • @Abhinay 一个普通的f.check_boxuser_receives_updates 输出为id,这是正确的值

标签: ruby-on-rails actionview form-helpers


【解决方案1】:

我回到check_box_tag 的文档中,对它有了更多的了解。我最终选择了这个:

module FormHelper
  def wrapped_check_box_tag(name, value=1, checked=false, options={})
    raw "<div class='checkbox-wrapper'>" + \
      check_box_tag(name, value, checked, options) + \
      "<span class='checkbox-checks'></span>" + \
    "</div>"
  end

  class ActionView::Helpers::FormBuilder
    include FormHelper
    include ActionView::Helpers::FormTagHelper
    include ActionView::Helpers::FormOptionsHelper

    def wrapped_check_box(name, options = {})
      wrapped_check_box_tag("#{@object_name}[#{name.to_s}]", options[:value], options[:checked], options)
    end
  end
end

现在可以使用全局方法和表单助手:

&lt;%= wrapped_check_box_tag :accepts_terms %&gt;

&lt;%= f.wrapped_check_box :receives_updates, { checked: true } %&gt;

如果有人有任何建议,我会全力以赴!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2015-07-30
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多