【问题标题】:Simple_form & Nested attributes save blank model because of date attributes由于日期属性,Simple_form 和嵌套属性保存空白模型
【发布时间】:2017-08-04 12:52:59
【问题描述】:

模型用户

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 个字段“月”和“年”

如果我提交表单,则参数为空字段:

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

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

此参数不为空(表示不显示在视图上的日期值),并且不允许完成嵌套属性“reject_if: :all_blank”的条件

如果月份和年份为空,是否可以更改日期的值? 谢谢

【问题讨论】:

  • 您可以通过将表单中的 as: :date 替换为 as: :string 来使其正常工作。
  • 这会改变输入的行为,这不是获得良好用户体验的最佳方式
  • 是的,你是对的。我过去也遇到过这个问题,并试图记住我是如何解决它的。 This 可能是一种选择。
  • 有趣,但在这种情况下,我认为删除输入中的“discard_day: true”会更好:(
  • @Etienne 您是否尝试从允许的参数中删除 start_date(3i)?

标签: ruby-on-rails simple-form nested-attributes cocoon-gem


【解决方案1】:

我终于找到了办法:

如果另一个输入为空(在本例中为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2022-01-21
    相关资源
    最近更新 更多