gpt4 book ai didi

ruby-on-rails - 为什么我的 person_ids 哈希中有一个空数组元素?

转载 作者:数据小太阳 更新时间:2023-10-29 08:38:29 25 4
gpt4 key购买 nike

在我的 Rails 应用程序中,我有这个模型:

class Project < ActiveRecord::Base

attr_accessible :name, :person_ids

belongs_to :user

has_many :people_projects
has_many :people, :through => :people_projects

end

我不明白的是:

当我创建一个新项目时,为什么我的 person_ids 数组的开头总是有一个空元素:

Parameters: {"utf8" => "✓", "project" => {"name" => "Testproject", "person_ids" => ["", "1", "2", "3"]}, "commit" => "Create", "id"=>"77"}

这不仅发生在我的 Project 类中,而且发生在所有其他具有 has_many through 的类中,这给我带来了很多(主要是与验证相关的)麻烦。

这是我的表格:

<div class="field">
<%= f.label "People" %>
<%= f.select(:person_ids, current_user.people.map { |p| [ p.name, p.id ] }, {}, {:multiple => true}) %>
</div>

感谢任何可以阐明这一点的人。

最佳答案

我想也许我已经找到了问题所在。看起来它来自 {:multiple => true} 正如 Mike A. 指出的那样在 this回答:

来自select docs :

Gotcha

The HTML specification says when multiple parameter passed to select and all options got deselected web browsers do not send any value to server. Unfortunately this introduces a gotcha: if an User model has many roles and have role_ids accessor, and in the form that edits roles of the user the user deselects all roles from role_ids multiple select box, no role_ids parameter is sent. So, any mass-assignment idiom like

@user.update_attributes(params[:user])

wouldn’t update roles.

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.

This way, the client either sends only the hidden field (representing the deselected multiple select box), 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.

所以这是一个有意义的计划功能,但它可能有一个阴暗面(如您的情况)- 根据 this answer,显然这在 Rails 4 中正在更改来自同一个链接问题。

You will be able to pass :include_hidden option. https://github.com/rails/rails/pull/5414/files

同一篇文章提供了这个解决方案,它删除了模型级别的所有空白值:

before_validation do |model|
model.subset_array.reject!(&:blank?) if model.subset_array
end

关于ruby-on-rails - 为什么我的 person_ids 哈希中有一个空数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745592/

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