[英]Rails Convert date_select to an int value
在Rails 3.x中,我有一个带有int字段“ my_int_date”的模型类。 我希望将int字段填充为date_select表单元素的表单。
问题是,当表单读取date_select值时,它会以多参数值的形式将其发送回,从而导致错误
1 error(s) on assignment of multiparameter attributes
无论如何,我可以将其作为日期存储在模型中,但是在将其转储到数据库时将其转换为int吗?
Ruby可以使用to_i将Time对象转换为秒
Time.now.to_i # Returns epoc time (s)
如果是字符串,则可以使用to_time方法
'2012-06-01'.to_time.to_i # string to Time object then to epoc time (s)
这是我解决的方法
在我的ActiveRecord模型中,我添加了字段
attr_accessible :my_int_date_time
columns_hash["my_int_date_time"] = ActiveRecord::ConnectionAdapters::Column.new("my_int_date_time", nil, "DateTime")
def my_int_date_time
return TimeHelper.datetime_from_integer(self.my_int_date)
end
def my_int_date_time= val
self.my_int_date = TimeHelper.datetime_to_integer(val)
end
然后在我的表单中,将datetime字段链接到my_int_date_time字段,而不是将其链接到my_int_date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.