Set a Date Attribute from date_select Without Mass Assignment in Ruby On Rails

Posted on 29 May 2008 by Johannes Fahrenkrug. Tags: Programming Ruby rails
This has been talked about a million times, but I just ran into this problem again and want to share the solution: You have a date_select helper in your Rails view and you want to assign the selected date to your model. With mass assignment that's not a problem, but when you try this:
@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)   
  end
Now 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:
Recommend Me
Thank you!

Comments

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.

August 27, 2008 11:40 AM

bbnnt said...

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.

August 27, 2008 11:29 AM

Anonymous said...

Thanks a lot for this useful trick!
S.

August 17, 2008 06:47 PM

Comments

Please keep it clean, everybody. Comments with profanity will be deleted.

blog comments powered by Disqus