That just initializes it before the object is saved to the db (but only
when it’s created, not if it was already pulled from the db and is now
being saved).
I’m having a similar problem, because I’d like to initialize strings
when a new object is made. For example
o = MyClass.new
o.name += “the name”
This will fail because o.name is nil. I’d like o.name to be an empty
string (’’) so that += will work fine. It’s quite bothersome having to
check for nil and then initialize before I make any +=
but otherwise have rails continue to manage instantiation.
Rails doesn’t follow typical object instantiation paths when creating
objects for you. When you
create an instance of a class by calling the ‘new’ method, the new
method is responsible for
invoking your ‘allocate’ and ‘initialize’ methods. Rails doesn’t do
this.
Rails instead uses Class#allocate by itself to allocate space for your
instance, but it never
initializes it. I don’t know why the Rails team did this for certain,
but my guess is for
performance benefits.
You can override this behavior by overriding the allocate method on
specific models or by overriding
ActiveRecord::Base for it to take affect on all models.
class ActiveRecord::Base
def self.allocate
instance = super
instance.send :initialize
instance
end
end
class MyModel < ActiveRecord::Base
attr_accessor :x
Now take note that setting default instance variables in your model
doesn’t mean their going to get
put into your database, you need to make sure you add them to the @attributes hash if you want them
to do that, and you dont’t want to set those in your ‘initialize’ method
because Rails will override
them when it pulls information from the database.