rubydatabaseactiverecordsqlitecolumn-defaults

ActiveRecord is showing wrong column defaults


This is my first time using ActiveRecord in a non-rails application, and I'm running into a problem. ActiveRecord is able to figure out the columns I have in my sqlite3 database, but it can't figure out the default column values for some reason.

Here is the sql description for the table in question.

-- Describe ACCOUNTS
CREATE TABLE "accounts" (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT (0),
    "username" TEXT NOT NULL,
    "password_hash" BLOB NOT NULL,
    "creation_time" INTEGER NOT NULL DEFAULT(strftime('%s', 'now')),
    "expiration_time" INTEGER NOT NULL DEFAULT(strftime('%s', 'now') + 2592000)
)

I used the following code for loading my database file.

require 'active_record'
require './config.rb'

ActiveRecord::Base.establish_connection(
  :adapter  => 'sqlite3',
  :database => DB_FILE
)

class Account < ActiveRecord::Base
end

When I look at the column defaults for the Account table with a REPL, this is what I get:

[10] pry(main)> Account.column_defaults
=> {"id"=>0,
 "username"=>nil,
 "password_hash"=>nil,
 "creation_time"=>0,
 "expiration_time"=>0}

I worked with ActiveRecord for a rails app before and it was smart enough to figure out the default values. For some reason, it can't figure them out now.

Am I doing something wrong here? I read that I can manually specify the default value with default :id => bla, but shouldn't ActiveRecord be able to figure out the defaults?


Update: I think I figured out a workaround. The hash returned by Account.column_defaults is writeable, and changing those elements seems to work fine.


Solution

  • Try doing this:

    class Account < ActiveRecord::Base
      after_initialize :default_values
    
      private
        def default_values
          self.username ||= "default value"
          #etc...
        end
    end