I would do two things here:
Do not allow NULLs in the capital
column. Allowing NULLs is the Rails default but it is almost always the wrong choice so make the column NOT NULL by hand. You might want to apply this to all the other columns in your tables too: if you can't justify allow NULLs in a column, make it NOT NULL.
Include a default value – in the database, not just in your Rails code – for the capital
column.
This would make migration 2 look like:
change_table :cities do |t|
t.boolean :capital, :null => false, :default => false
end
If you do both of those then the database will fill in the defaults when it adds your new column and your problem goes away.
I tend to treat the database as an entirely separate application unto itself whose interface happens to be SQL (mostly) hidden behind ActiveRecord or some other ORM.
I'd also agree with the commenters that using models inside your migrations is a bad idea.
BTW, your set_capital
method doesn't do what you think it does. You want to say:
def set_capital
self.capital = false
true
end
capital = false
only creates a local variable and then set_capital
will return false
; so your set_capital
won't initialize the capital
attribute and a before_*
callback return false
will stop everything in its tracks:
Canceling callbacks
If a before_*
callback returns false
, all the later callbacks and the associated action are cancelled.