如何将从 rails 中的 date_select 返回的哈希值转换为 Date 对象? [英] how to convert a hash value returned from a date_select in rails to a Date object?

查看:46
本文介绍了如何将从 rails 中的 date_select 返回的哈希值转换为 Date 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中的视图中有一个 date_select,但是在提交时返回的值是一个散列形式,如下所示:

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"}

如何将其转换为 Rails 中的日期格式,以便在查询数据库时将其用作条件,例如 :condition =>{:dates == :some_date_from_date_select}?我尝试调用 Date.parse(:some_date_from_date_select) 但它不起作用,因为它需要一个字符串而不是哈希映射.

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?

谢谢

推荐答案

我不知道 rails 的方式,但是这个one-liner"可以解决问题:

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"

或者,用更少的魔法:

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"

这篇关于如何将从 rails 中的 date_select 返回的哈希值转换为 Date 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆