I have a period model, containing start_date and end_date. It belongs to a Topic model.
In my topic form, I want to manage the period as well. So first I just used two text fields for the two dates in the period. I also have a reject_if end_date is nil.
accepts_nested_attributes_for :period,
reject_if: lambda { |p| p[:end_date].blank? }
It works. And a few months later I changed form to use date_select, that displays a few select statements for inputting date.
When I did this, I found out that each select will be something like this:
<select name="topic[period_attributes][end_date(1i)]" id="topic_period_attributes_end_date_1i">
Notice the 1i
, which means my reject_if no longer works, as anything will be rejected. I need to change to:
accepts_nested_attributes_for :period,
reject_if: lambda { |p| p[:'end_date(1i)']].blank? }
This would work, but it's not as good as before (checking only year of a date seems error prone).
Is there a correct way to do reject when I use date_select?
You can add a class helper method that checks all portions of the :end_date
attribute:
def self.date_populated?(params)
['1i', '2i', '3i'].select{|date_part|
params[:"end_date(#{date_part})"].blank?
}.blank?
end
and check the helper:
reject_if: lambda { |p| !date_populated?(p) }