Simple_form&嵌套属性节省,因为日期的空白模型属性

问题描述:

模型用户Simple_form&嵌套属性节省,因为日期的空白模型属性

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

如果我提交我的形式,用空场的PARAMS是:

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

我的问题: “起始日期(3I)”=> “1”

这PARAMS不是空白(这是代表并且不允许完成嵌套属性的条件“reject_if :: all_blank”

如果月份和年份是空白的,有一种方法可以更改一天的值吗? THX

+0

你可能通过在表单中​​用'as::string'替换'as::date'来实现它。 – Belder

+0

这改变了输入的行为,它不是一个良好的用户体验的最佳途径 – Etienne

+0

是的,你是对的。我过去也遇到过这个问题,并且想要记住我是如何解决它的。 [这](https://*.com/questions/29075404/how-can-i-generate-inputtype-date-with-simple-form)可能是一个选项。 – Belder

我终于找到了一个方法:

我创建了一个条件测试,如果另一个输入为空(在这种情况下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