The next problem to solve was this:
When we create model class like this
class CreateSubjects < ActiveRecord::Migration
def self.up
create_table :subjects do |t|
t.column :first_name, :string
t.column :last_name, :string, :null => false
t.column :age, :integer
end
end
...
end
we suggested that
first_name and
age should contain NULL values. But our suggestion on MS SQL Server was wrong (on postgreSQL is everything fine).
>> Subject.new
=> #<subject:0x495357c @new_record=true, @attributes={
"first_name"=>"NULL", "last_name"=>nil, "age"=>0}>
and we have string "NULL" in
first_name and 0 in
age columns after calling save! method. In
development.log was this create table script:
CREATE TABLE subjects ([id] int NOT NULL IDENTITY(1, 1) PRIMARY KEY, [first_name] varchar(255) DEFAULT NULL, [last_name] varchar(255) NOT NULL, [age] integer DEFAULT NULL)
Adding of "DEFAULT NULL" causes creation of default values (0 or "NULL") in sqlserver adapter. So, I created my first ticket in rails (
http://dev.rubyonrails.org/ticket/9469) with proposed solution and made this solution in our project:
# bugfix for mssql adapter - adding default value for columns
module ActiveRecord
module ConnectionAdapters # :nodoc:
module SchemaStatements
alias_method :old_add, :add_column_options!
attr_writer :adapter
def adapter
if @adapter.nil?
c = Rails::Configuration.new
env = ENV['RAILS_ENV'] ||= "development"
@adapter = c.database_configuration[env]['adapter']
end
@adapter
end
def add_column_options!(sql, options) #:nodoc:
if adapter === "sqlserver"
sql << " NOT NULL" if options[:null] == false
sql << " DEFAULT #{quote(options[:default], options[:column])}" unless options[:default].nil?
else
old_add sql, options
end
end
end
end
end