Model User
class User < ApplicationRecord
has_many :experiences, dependent: :destroy
accepts_nested_attributes_for :experiences, reject_if: :all_blank, allow_destroy: true
end
Model Experience
class Experience < ApplicationRecord
belongs_to :user
end
My input in the 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>
=> So, that is displaying 2 fields "Month" and "Year"
If I submit my form, with a empty field the params are:
"expertise"=>"", "start_date(3i)"=>"1", "start_date(2i)"=>"", "start_date(1i)"=>""
My problem: "start_date(3i)"=>"1"
This params is not blank (it's represent the day value which is not displayed on the view), and not permit to completed the condition of nested attributes "reject_if: :all_blank"
There is a way to change the value of a day if month and year is blank? Thx
答案 0 :(得分: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