【问题标题】:Form input requiring field to not be null表单输入要求字段不为空
【发布时间】:2019-10-27 06:18:33
【问题描述】:

我正在将我的应用程序从 rails 4.2 转移到 5.2,在这个转换过程中,我偶然发现了一个我不知道如何修复的错误。这段代码是为我编写的,因为当时我不知道如何完成它。我的桌子是为人准备的,桌子上有老板和非老板,这些非老板需要能够依附于老板。

在新的开发区,当我提交更新“老板”需要为null 的人的表单时,我得到以下信息: 1 error prohibited this person from being saved: Boss must exist

控制器:

def edit
    @person = Person.find(params[:id])
end

型号:

belongs_to :boss, class_name: 'Person'
has_many :subordinates, class_name: 'Person', foreign_key: 'boss_id'

validates_presence_of :user_name, :position, :fname, :lname 

架构:

t.integer "boss_id"
t.index ["boss_id"], name: "index_people_on_boss_id"

表格:

<% if @person.errors.any? %>
        <div id="error_explanation">
            <h2><%= pluralize(@person.errors.count, "error") %> prohibited this person from being saved:</h2>

            <ul>
                <% @person.errors.full_messages.each do |msg| %>
                  <li><%= msg %></li>
                <% end %>
            </ul>
        </div>
    <% end %>

    <fieldset>
        ...many fields...
    </fieldset>
    <fieldset>
        <label>
            Boss
            <%= f.select :boss_id, [[" ", :null], [name, 1], [name, 2], ...etc ] %>
        </label>
    </fieldset>
<%= f.submit %>
<% end %>

我不知道在哪里可以找到答案。

【问题讨论】:

  • 显示您的表单代码。
  • @MaxVinícius 表单代码已添加到帖子中。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

Belongs_to 要求父对象在创建时默认存在。如果您创建一个没有父对象的子对象,您将收到 ["must exist"] 错误消息,因此您的对象无效。

如果你想要这种行为,你需要传递这个选项:

#person.rb
belongs_to :boss, class_name: 'Person', optional: true

【讨论】:

猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多