【问题标题】:Rails: test if a column allows nil valuesRails:测试列是否允许零值
【发布时间】:2014-08-05 20:06:37
【问题描述】:

Rails: Force empty string to NULL in the database 的这个答案建议使用 mixin 将空字符串列值设置为 nil。

有没有办法测试列是否接受 nil/null 值?

> f = Foobar.find(1)
=> #<Entity id: 7, name: "foo", description: nil, has_bar: false, created_at: "2014-08-04 21:50:42", updated_at: "2014-08-05 19:35:33">

> f.has_bar.allow_nil?
NoMethodError: undefined method `allow_nil?' for nil:NilClass

我想确保description 字段是nil 不是空白字符串,但要确保has_bartruefalse

摘自其他问题:

attributes.each do |column, value|
  # invalid syntax
  ( self[column].present? && self[column].allow_nil? ) || self[column] = nil
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:
    f.description.nil? && (f.has_bar == true || f.has_bar == false)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多