Re: ActiveRecord uses confusing defaults

Jeroen
Sat, 09 Sep 2006 10:27:15 -0000

Rick Olson wrote:
>> Hey that''s interesting.
>>
>>     t.column "email", :string, :default => "",
:null => false
>
> So my point was, setting the column default to "" means
it''s default
> upon AR model initialization.  If you set this up with :null => false
> (or NOT NULL), your DB probably won''t let you save NULL to the
> attribute.  Quit setting these confusing defaults, and you''ll stop
> seeing them in AR.
>

Okay I''m *almost* starting to feel stupid here, but I am not setting
these defaults myself. Please take one more look at the stuff below.

Just ran another test with a blank database:

class AddTestTable < ActiveRecord::Migration
  def self.up
    create_table "contents", :force => true do |t|
      t.column "email", :string, :null => false
    end
  end

  def self.down
    drop_table "contents"
  end
end

$ script/generate model Content

$ script/console

Loading development environment.
>> Content.new.email
=> ""
>>

I just dont understand why it defaults to "" and not to nil. Nowhere
did
I set the default to "" in my migrations file.

Now if I do $rake db:schema:dump here''s what the generated schema looks
like:

# This file is autogenerated. Instead of editing this file, please use
the
# migrations feature of ActiveRecord to incrementally modify your
database, and
# then regenerate this schema definition.

ActiveRecord::Schema.define(:version => 1) do

  create_table "contents", :force => true do |t|
    t.column "email", :string, :default => "", :null
=> false
  end

end

All of a sudden there is a :default=>""

Okay, now I add another column, here''s the migration:

class AddIntCol < ActiveRecord::Migration
  def self.up
    add_column :contents, :mynum, :integer, :null => false
  end

  def self.down
  end
end

Now in script/console

>> Content.new
=> #<Content:0x2449804 @attributes={"mynum"=>0,
"email"=>""},
@new_record=true>

Why is mynum set to 0 ?

$ rake db:schema:dump

  create_table "contents", :force => true do |t|
    t.column "email", :string, :default => "", :null
=> false
    t.column "mynum", :integer, :default => 0, :null => false
  end


Why the :default => 0 ?

As you can see, it''s not in MySql:

mysql> show fields from contents;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| email | varchar(255) | NO   |     |         |                |
| mynum | int(11)      | NO   |     |         |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.26 sec)


Again, I apologize if this is normal and this is how things should work,
it just seems odd to me.

Jeroen