gpt4 book ai didi

ruby-on-rails - 具有多个 true 的 collection_select 发送带有空字符串的参数

转载 作者:行者123 更新时间:2023-12-02 21:11:26 24 4
gpt4 key购买 nike

我的应用程序中的 select_options 标记生成一个参数列表,该列表始终在开头包含一个空字符串。当使用参数从数据库获取数据时,这会导致错误。

表单部分是这样的:

<%= f.label :text %><br>
<%= f.text_area :text, cols: 80, rows: 15, class: 'form-control' %>


<%= f.label 'Category:' %>

<%= f.collection_select(:categories, Category.all, :id, :cat_name, {:selected => Category.first.id}, {:multiple => true}) %>

输出(html)是这样的:

<select multiple="multiple" name="article[categories][]" id="article_categories">
<input name="article[categories][]" value="" type="hidden">
<option selected="selected" value="1">default</option>
<option value="2">politics</option>
</select>

这对我来说看起来很完美。但提交后(选择了两个选项)参数如下所示:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"kvYo6rb+lswUuJMHpbb+hH3YFjHU25/ESN7vvLLdlVn1TOSgzyiMsXkrJbiWIhuuO4UvNLQ3jU7uTw0zneVTUA==", 
"article"=>{"title"=>"test category", "text"=>"Na mal sehen...\r\nIses drin?",
"categories"=>["", "1", "2"], "published"=>"0"}, "commit"=>"Save changes", "id"=>"76"}

类别部分包含:categories"=>["", "1", "2"]第一个是一个空字符串,我不知道如何摆脱它。

提前感谢您的帮助!

最佳答案

Rails 生成一个与选择字段同名的隐藏字段,因此如果没有选择任何选项,仍然会提交一个值。您可以通过为 collection_select 指定 include_hidden: false 来阻止 Rails 添加隐藏字段。

以下是解释摘录 ( link ):

To prevent this the helper generates an auxiliary hidden field before every multiple select. The hidden field has the same name as multiple select and blank value.

Note: The client either sends only the hidden field (representing the deselected multiple select box), or both fields. This means that the resulting array always contains a blank string.

In case if you don’t want the helper to generate this hidden field you can specify include_hidden: false option.

关于ruby-on-rails - 具有多个 true 的 collection_select 发送带有空字符串的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220548/

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