【问题标题】:Why does Rails save String as null to date time column?为什么 Rails 将 String 保存为 null 到日期时间列?
【发布时间】:2010-07-29 16:12:35
【问题描述】:

我在测试验证时遇到了这种特质。迁移定义如下:

create_table :time_windows do |t|
  t.datetime :window_begin, :null => true
  t.datetime :window_end, :null => true
end

在 irb 中

>> t = TimeWindow.new({:window_begin  => Time.now, :window_end => "not a time"})
=> #<TimeWindow id: nil, window_begin: "2010-07-29 15:54:07", window_end: nil>

我的问题是,为什么 ActiveRecord 将“not a time”解释为 nil 而不仅仅是设置 :window_end = “not a time”?当您将 :window_end 设置为 int 时,也会发生相同的转换为 nil。

这对我来说是个问题的原因是,如果有人试图在 :window_end(或 :window_start)列中保存非时间值,我希望抛出一个错误,但这里不会出现这种情况.

谢谢。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-migrations


    【解决方案1】:

    首先,数据库不能在日期时间列中保存字符串。其次,Rails 将“not a time”解释为 nil,因为您没有时间价值,即您有 nil。

    最后,验证您的输入是您的责任。你可以这样做:rails built in datetime validation

    【讨论】:

    • 我认为我的问题措辞不当。暂时忘记将其保存到数据库中。当我在内存中为 :window_end 属性创建具有非法(不是时间)值的 TimeWindow 对象时,它只是用 nil 为 :window_end 实例化该对象。但是,如果我使用整数类型的属性 :count 实例化一个不同的模型类,并分配 :count => "not a number",则该对象将使用 :count = "not a number" 进行实例化。为什么前一种情况下 String -> nil 的翻译,而后一种情况下没有?
    • 整数属性不是这样。我刚刚在我的一个项目中进行了以下操作: u = User.new(:sign_in_count => "not a number") [btw, sign_in_count is integer attr] 当我调用 u.sign_in_count 时,我得到:0。原因是因为 "not a number" 是使用 to_i 转换的,它返回 0 ("not a number".to_i => 0)
    猜你喜欢
    • 2016-05-09
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2019-10-20
    相关资源
    最近更新 更多