A Ruby on Rails plugin that treats a column as a boolean, whether it’s
a tinyint, integer, float, string, etc. No matter how true and false are
stored in the database.
This is useful when you don’t have control over how booleans are
stored by different applications. For example: Microsoft Access stores
booleans as 0 and -1. Normally -1 in a MySQL database, would be
converted, by Rails/ActiveRecord, into a false, rather than true as it should be.
You can use either foo (assuming your column is foo) or foo? methods and
they return the same result.
The following are false (lower or any case), all else are true:
false, nil, 0, 0.0, ‘’, ’0’, ‘0.0’, ‘f’, ‘false’, ‘n’, ‘no’, ‘negative’,
[], {}
You can add to these, for individual columns, using the false_is_also
parameter.
Note: if you use the set_false_as parameter, it will automatically be added
to the list of falses for this column.
You can specify a specific way a boolean should be stored when
assigned with set_false_as and set_true_as. This, however, will not change
how the value is evaluated on read. In other words, if you save a false as
‘nope’, a value of ‘0’ or ‘f’ in the database will still be read as a false.
It only affects how it is stored.
The values set with set_true_as and set_false_as have to be appropriate
for the field type. You, obviously, can’t store ‘foo’ in an integer field.
Also note that boolean type fields can’t have set_false_as or
set_true_as set, because booleans are stored differently in different
databases (for example: ‘t’ and ‘f’ in sqlite and 0 and 1 in others).
However, acts_as_boolean is still useful for booleans, to correctly
convert something like a -1 to true.
- set_false_as – What false value to store in the column on assignment.
By default any value will be stored, and converted to
true or false when you read the value. - set_true_as – What true value to store in the column on assignment.
By default any value will be stored, and converted to
true or false when you read the value. - false_is_also – Additional values to be treated as false
The most simple example is when you want column foo to return true
and false correctly for both foo and foo? methods. To do that,
simply add the following to your model:
acts_as_boolean :foo
Some other examples:
class Person < ActiveRecord::Base
acts_as_boolean :alive, :employee
acts_as_boolean :vendor, :client, :set_true_as => -1
acts_as_boolean :foo, :false_is_also => ['nine', 'nada', 9999]
acts_as_boolean :bar, :set_false_as => 'no', :set_true_as => 'yes', :false_is_also => 'nyet'
#...
end
For Rails 2.1 and above:
ruby script/plugin install git://github.com/twerth/acts_as_boolean
To upgrade:
ruby script/plugin install git://github.com/twerth/acts_as_boolean.git —force
Released under the MIT license