1

I have boolean column in my DB (.sqlite3). It may be 't' or 'f'.

t.boolean :disable_product_category

How can I change the value to 1 or 0?

EDIT: I find this Rails 3 SQLite3 Boolean false

I edit active_record/connection_adapters/abstract/quoting.rb.

if column && column.type == :integer
  value ? 1 : 0
else
  value ? 't' : 'f'
end

After replaced 't' and 'f' to 1 and 0, all work as I want.

Is that normal solution? I want use this:

# config/initializers/sqlite3_adapter_patch.rb

module ActiveRecord
  module ConnectionAdapters
    class SQLite3Adapter < AbstractAdapter
      QUOTED_TRUE, QUOTED_FALSE = "'t'", "'f'"

      def quoted_true
        QUOTED_TRUE
      end

      def quoted_false
        QUOTED_FALSE
      end
    end
  end
end

But it is not work :(. Is it need update the application somehow?

Community
  • 1
  • 1
ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35

2 Answers2

0

A boolean may have an internal representation of 't', 'f', 1 or 0, but in your code you can treat the value of the column as an ordinary boolean value.

Add a default argument to set the default value for the column:

t.boolean :disable_product_category, default: false
zwippie
  • 15,050
  • 3
  • 39
  • 54
  • I use this DB in Rails and Java app. Java app use OrmLite which operate with 0 and 1 boolean values. I need change char ('t' or 'f') boolean value on Rails to 1 or 0. – ViT-Vetal- Apr 18 '14 at 13:21
0

Boolean datatypes are stored in integers 0 (false) and 1 (true). As you've mentioned that your disable_product_category comes in as either t or f, your concern should be in the translation of these literals to appropriate boolean value so that correct value is written to the database.

To achieve this you could override the setter for disable_product_category and do the appropriate translation, e.g.

class Foo < ActiveRecord::Base

  def disable_product_category=(value)
    value = true if value == 't'
    value = false if value == 'f' 
    super(value)
  end
end
vee
  • 38,255
  • 7
  • 74
  • 78
  • could simplify with `super(value == 't')` – Kyle Apr 18 '14 at 13:27
  • @Kyle, sure, I understand your concern, the code can be compacted. On a side note however, `nil`/ `DBNULL` is also a possible value, `super(value == 't')` will make all values except `t`, `false`? – vee Apr 18 '14 at 13:30
  • But in DB is 'f'. **def disable_category=(value) super(0) end** – ViT-Vetal- Apr 18 '14 at 13:38
  • http://www.sqlite.org/datatype3.html "SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true)." Why in rails is 't' or 'f'? – ViT-Vetal- Apr 18 '14 at 14:12
  • @ViT-Vetal-, it shouldn't be `t` or `f` if it's a boolean column. Could you be overriding the getter in the model and doing a translation there? – vee Apr 19 '14 at 00:26