Using select_date gives me back a params[:my_date] with year, month and day attributes. How do get a Date ob
I use the following method, which has the following benefits:
xxx(1i) through xxx(3i) (and thus could be modified to capture hour and minute simply by changing Date to DateTime); andparams even when those params are populated with many other key-value pairs.params is a hash of the format { xxx(1i): '2017', xxx(2i): 12, xxx(3i): 31, ... }; date_key is the common substring xxx of the target date parameters.
def date_from_params(params, date_key)
date_keys = params.keys.select { |k| k.to_s.match?(date_key.to_s) }.sort
date_array = params.values_at(*date_keys).map(&:to_i)
Date.civil(*date_array)
end
I chose to place this as a class method of ApplicationRecord, rather than as an instance helper method of ApplicationController. My reasoning is that similar logic exists within the ActiveRecord instantiator (i.e., Model.new) to parse dates passed in from Rails forms.