Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

how to convert a hash value returned from a date_select in rails to a Date object?

I have a date_select in my view inside a form, however on submit the value returned is in a hash form like so:

{"(1i)"=>"2010", "(2i)"=>"8", "(3i)"=>"16"}

how can i convert that in to a Date format in rails so i can use it as a condition when querying the database e.g :condition => {:dates == :some_date_from_date_select}? i tried calling Date.parse(:some_date_from_date_select) but it didn't work because its expecting a string and not a hash map.

is there a rails way to do this?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know about a rails way, but this "one-liner" does the trick:

irb(main):036:0> d = Date.parse( {"(1i)"=>"2010", "(2i)"=>"8", "(3i)"=>"16"}.to_a.sort.collect{|c| c[1]}.join("-") )
=> #<Date: 4910849/2,0,2299161>
irb(main):037:0> d.to_s
=> "2010-08-16"

Or, with less magic:

h={"(1i)"=>"2010", "(2i)"=>"8", "(3i)"=>"16"}
d=Date.new(h['(1i)'].to_i, h['(2i)'].to_i, h['(3i)'].to_i)
d.to_s
=> "2010-08-16"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...