gpt4 book ai didi

ruby-on-rails - 默认情况下 simple_form - collection_check_boxes 在末尾显示 hidden_​​field

转载 作者:行者123 更新时间:2023-12-04 22:21:04 27 4
gpt4 key购买 nike

我在 new.html.erb 中使用 simple_form 的 collection_check_boxes。默认情况下,当 html 被渲染时,它会在最后添加隐藏字段,因为在 Controller 端我得到最后一个元素为“”的值数组。任何人都可以帮助我如何防止隐藏字段在 View 上呈现?

新的.html.erb:

<%= f.collection_check_boxes :topic_id, Topic.all, :id, :name %>
<%= f.button :submit %>

我使用 Firebug 检查我的复选框元素,结果如下:
    <span>
<span>
<input type="hidden" value="" name="revision[topic_id][]">
<input class="btn" type="submit" value="Create Revision" name="commit">

我想删除上面的隐藏字段。请帮忙。

最佳答案

隐藏字段是故意存在的,您可能不想删除它。用于处理未选中复选框的情况。

我认为 simple_form 最终会回到标准 FormBuilder 中相同的基本 check_box 逻辑上。这里有一些文档说明了为什么复选框具有该隐藏字段。从 check_box documentation :

# The HTML specification says unchecked check boxes are not successful, and
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
# any mass-assignment idiom like
#
# @invoice.update(params[:invoice])
#
# wouldn't update the flag.
#
# To prevent this the helper generates an auxiliary hidden field before
# the very check box. The hidden field has the same name and its
# attributes mimic an unchecked check box.
#
# This way, the client either sends only the hidden field (representing
# the check box is unchecked), or both fields. Since the HTML specification
# says key/value pairs have to be sent in the same order they appear in the
# form, and parameters extraction gets the last occurrence of any repeated
# key in the query string, that works for ordinary forms.

标准 collection_check_boxesexample 显示隐藏字段:
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
#
# If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
# <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
# <label for="post_author_ids_1">D. Heinemeier Hansson</label>
# <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
# <label for="post_author_ids_2">D. Thomas</label>
# <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
# <label for="post_author_ids_3">M. Clark</label>
# <input name="post[author_ids][]" type="hidden" value="" />

关于ruby-on-rails - 默认情况下 simple_form - collection_check_boxes 在末尾显示 hidden_​​field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20744435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com