【问题标题】:Rails Convert date_select to an int valueRails 将 date_select 转换为 int 值
【发布时间】:2012-08-06 21:45:10
【问题描述】:
在 Rails 3.x 中,我有一个带有 int 字段“my_int_date”的模型类。我希望 int 字段由作为 date_select 表单元素的表单填充。
问题是当表单读取 date_select 值时,它会将其作为多参数值发送回来,这会导致错误
1 error(s) on assignment of multiparameter attributes
我是否可以将它作为 Date 存储在我的模型中,但在将其转储到 DB 时将其转换为 int?
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-3
ruby-on-rails-3.1
ruby-on-rails-3.2
【解决方案1】:
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)
【解决方案2】:
我是这样解决的,
在我的 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
然后在我的表单中,我将日期时间字段链接到字段 my_int_date_time,而不是将其链接到 my_int_date