Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Date from date_select or select_date in Rails?

Using select_date gives me back a params[:my_date] with year, month and day attributes. How do get a Date object easily? I'm hoping for something like params[:my_date].to_date.

I'm happy to use date_select instead as well.

like image 440
at. Avatar asked Nov 28 '12 12:11

at.


2 Answers

Using date_select gives you 3 separate key/value pairs for the day, month, and year respectively. So you can pass them into Date.new as parameters to create a new Date object.

An example date_select returned params for an Event model:

"event"=>
 {"name"=>"Birthday",
  "date(1i)"=>"2012",
  "date(2i)"=>"11",
  "date(3i)"=>"28"},

Then to create the new Date object:

event = params[:event]
date = Date.new event["date(1i)"].to_i, event["date(2i)"].to_i, event["date(3i)"].to_i

You may instead decide to wrap this logic in a method:

def flatten_date_array hash
  %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end

And then call it as date = Date.new *flatten_date_array params[:event]. But this is not logic that truly belongs in a controller, so you may decide to move it elsewhere. You could even extend this onto the Date class, and call it as date = Date.new_from_hash params[:event].

like image 149
joofsh Avatar answered Sep 20 '22 15:09

joofsh


Here is another one:

# view
<%= date_select('event', 'date') %>

# controller
date = Date.civil(*params[:event].sort.map(&:last).map(&:to_i))

Found at http://kevinlochner.com/use-rails-dateselect-without-an-activerecord

like image 30
Vassilis Avatar answered Sep 21 '22 15:09

Vassilis