@something.my_date = params[:something][:my_date]You will be disappointed and there will be wailing and gnashing of teeth. Why? Because date_select creates 3 form components and 3 corresponding values in the form and in the params[:something] hash, namely
params[:something][:my_date(1i)] params[:something][:my_date(2i)] params[:something][:my_date(3i)]These represent the year, the month and the day (Duh!). When you use @something.attributes= to mass assign this, ActiveRecord takes care of creating a date object from these three values (see attributes=, assign_multiparameter_attributes, extract_callstack_for_multiparameter_attributes, and execute_callstack_for_multiparameter_attributes). Sometimes you might not want to mass assign, though (security comes to mind). So what are you to do? Maybe putting this code (inspired by this code) in your application.rb might help:
private def convert_date(hash, date_symbol_or_string) attribute = date_symbol_or_string.to_s return Date.new(hash[attribute + '(1i)'].to_i, hash[attribute + '(2i)'].to_i, hash[attribute + '(3i)'].to_i) endNow you can assign dates from date_select like this:
@something.my_date = convert_date(params[:something], :my_date)Please comment if you have a better or more elegant solution! If this was useful for you, please take a minute and recommend me:
Johannes Fahrenkrug said...
Thanks for the comment, bbnnt, I'm glad it was helpful. Another Rails ebook I really like is the Rails 2.1 PDF by Peepcode, you should check it out.
Btw, I checked out your blog and I really like the video by Dr. Nic on iPhone testing with Ruby, thanks for that.
A great thank ! I don't know why this was that hard to find out a solution.
Anyway, there's this very good ebook wrote by carlos brando, ruby on rails 2.1, what's new; well, on page 67, it talks about the date_select helper, doesn't even work as it is shown !
I might not be aware about every rails evolutions, but it'd be great that a nice date solution could be integrated instead of having to rely n some plugins.
Thanks a lot for this useful trick!