How are values cast when assigning to a Boolean field in Rails ActiveRecord?

前端 未结 3 1309
醉酒成梦
醉酒成梦 2021-02-08 21:37

Short version of my question

In Rails ActiveRecord, if I have a Boolean field and I assign it something like \"abc\" or 2, the

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 22:02

    The behavior of boolean columns changed with two commits:

    • e01a46f (2014-10-17)
    • a502703 (2015-01-04).

    The new rule is very simple. See the code below:

    module ActiveRecord
      module Type
        class Boolean < Value # :nodoc:
          def type
        :boolean
          end
    
          private
    
          def cast_value(value)
        if value == ''
          nil
        else
          !ConnectionAdapters::Column::FALSE_VALUES.include?(value)
        end
          end
        end
      end
    end
    

    The constant ConnectionAdapters::Column::FALSE_VALUES is defined as follows:

    [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
    

    If a value is not an empty string and is not among them, it will be cast to true.

    This change will become effective on the Rails 5.0.

提交回复
热议问题