Simple_form & 由于日期属性,嵌套属性保存空白模型

Simple_form & Nested attributes save blank model because of date attributes

模范用户

class User < ApplicationRecord
  has_many :experiences, dependent: :destroy
  accepts_nested_attributes_for :experiences, reject_if: :all_blank, allow_destroy: true
end

模特经验

class Experience < ApplicationRecord
  belongs_to :user
end

我在 VIEW 中的输入 (_experience_fields_user.html)

<div class="nested-fields">
  <%= f.input :start_date as: :date, discard_day: true, order: [:month, :year], start_year: Date.today.year , end_year: Date.today.year - 37  %>
</div>

=> 因此,显示 2 个字段 "Month" 和 "Year"

如果我提交我的表单,其中有一个空字段,参数是:

"expertise"=>"", "start_date(3i)"=>"1", "start_date(2i)"=>"", "start_date(1i)"=>""

我的问题:"start_date(3i)"=>“1”

此参数不为空(表示视图中不显示的日期值),不允许完成嵌套属性的条件"reject_if: :all_blank"

如果月份和年份为空,有没有办法改变一天的值? 谢谢

终于找到方法了:

我创建了一个条件来测试另一个输入是否为空(在本例中 company_name)

在我的模型中用户:

accepts_nested_attributes_for :experiences, reject_if: :reject_xp, allow_destroy: true

def reject_xp(attributes)
   attributes['start_date(3i)'] == "1" && attributes['company_name'].blank?
end