Data from params (another solution)

There have been several postings about how to extract a :date out of
the params hash, none of which seem to make use of Rails own
functionality. When a model includes a :date field, the params list
coming back from a date_select view has multiple parts, each tagged
with something like “(1i)”. Rails calls these multi-parameter
attributes. When you pass the params list directly to a model’s new
method, Rails parses the date just fine:

my_model = MyModel.new(params[:my_model])

However, if you want to just snag an embedded date (say,
“entered_on”), it seemed like you were out of luck unless you did an
end-around and created your own Date object.

Perusing the source for ActiveRecord::Base, the initialize() method
(called by MyObject.new and its kin) includes this line:

self.attributes = attributes unless attributes.nil?

This line invokes ActiveRecord::Base::attributes=, which includes code
to handle multi-parameter attributes. Basically, it looks for the “(”
in the parameter name, causing it to invoke
assign_multiparameter_attributes, which does all the magic.

So the question is, how do we arrange for the multi-parameter
attribute for a date to be assigned to our model object? Here’s what
I came up with; I’d welcome a cleaner alternative.

my_model.attributes = params[:my_model].reject { |k,v| k !~ /
^entered_on/ }

This arranges to create a (new) hash containing just the muti-
parameter attribute “entered_on” (including “entered_on(1i)”,
“entered_on(2i)”, etc.), and pass the hash to the attributes= method,
which handles the date attribute.

tom.