“正确”在 Ruby 是个危险的词。做任何事情通常都有不止一种方法。如果您知道 一直都是希望该表上的列具有这个默认值,那么在 DB 迁移文件中设置它们是最简单的方法:
class SetDefault < ActiveRecord::Migration
def self.up
change_column :people, :last_name, :type, :default => "Doe"
end
def self.down
# You can't currently remove default values in Rails
raise ActiveRecord::IrreversibleMigration, "Can't remove the default"
end
end
class GenericPerson < Person
def initialize(attributes=nil)
attr_with_defaults = {:last_name => "Doe"}.merge(attributes)
super(attr_with_defaults)
end
end
在 Ruby on Rails v3.2.8中,使用 after_initialize ActiveRecord 回调,您可以调用模型中的一个方法,该方法将为新对象分配默认值。
对于查找器找到并实例化的每个对象,都会触发 after _ initialize 回调,而 after _ initialize 也会在新对象实例化后触发
(see ActiveRecord Callbacks).
因此,我认为它应该是这样的:
class Foo < ActiveRecord::Base
after_initialize :assign_defaults_on_new_Foo
...
attr_accessible :bar
...
private
def assign_defaults_on_new_Foo
# required to check an attribute for existence to weed out existing records
self.bar = default_value unless self.attribute_whose_presence_has_been_validated
end
end
class SetDefault < ActiveRecord::Migration
def up
# Set default value
change_column_default :people, :last_name, "Smith"
end
def down
# Remove default
change_column_default :people, :last_name, nil
end
end