我在new.html.erb中使用simple_form的collection_check_boxes。默认情况下,当渲染html时,它会在末尾添加隐藏字段,因为在控制器端我得到的值数组,最后一个元素为“”。任何人都可以帮助我如何防止隐藏字段在视图上呈现?
new.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">
我想删除上面的隐藏字段。请帮忙。
答案 0 :(得分:9)
对于执行想要删除空值的人,请使用include_hidden: false
param:
<%= f.collection_check_boxes :topic_id, Topic.all, :id, :name, include_hidden: false %>
目前API尚未记录,但它在那里:https://github.com/rails/rails/blob/master/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb
# Append a hidden field to make sure something will be sent back to the
# server if all check boxes are unchecked.
if @options.fetch(:include_hidden, true)
rendered_collection + hidden_field
else
rendered_collection
end
答案 1 :(得分:2)
隐藏字段是故意存在的,您可能不想删除它。它是在没有选中复选框时处理的情况。
我认为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_boxes
的{{3}}显示隐藏字段:
# 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="" />