A. Unger
A. Unger

Reputation: 13

Rails - How do I load a boolean variable initialized into the database

When I create an item in my application I want to load it as a boolean variable initialized to false, but everytime I check the object I create with the rails console it's initialized to null, so, how can I do that? (:

Upvotes: 0

Views: 312

Answers (2)

awendt
awendt

Reputation: 13633

You could simply override the getter in your model:

class MyModel < ActiveRecord::Base
  def object
    super || false
  end
end

That way it doesn't matter if it's NULL in the database.

Upvotes: 0

sevenseacat
sevenseacat

Reputation: 25029

The easiest way to do this is by setting the default value to false in your database migration.

ie. in a migration's up or change method:

add_column :your_table_name, :your_field_name, :boolean, :default => false (for a new column)

or:

change_column_default :your_table_name, :your_field_name, false (for an existing column)

Upvotes: 2

Related Questions