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
I finally found a way:
I created a condition for test if another input is empty (in this case company_name)
In my model User:
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