【问题标题】: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)
    

    【讨论】:

    • 谢谢,但我知道这种转换:/。我知道有一种方法可以将 date_select 解析为 dateTime,但对于应该如此常见的东西来说它看起来很乱。看到这个帖子stackoverflow.com/questions/5073756/…
    【解决方案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

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 2021-11-04
      • 2015-04-30
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2012-02-25
      相关资源
      最近更新 更多