Adding initialization to a model class


#1

How do add initialization to a model class that adds an attribute and
sets
its values? I tried adding an initialize method

def initialize
@x = ‘blah’
end

but I get a runtime exception:NoMethodError in Sites#new

I want the value of @x to be set when the “Site” model object is created
but
otherwise have rails continue to manage instantiation.

Thanks again.


#2

you could add a before_create filter…


#3

james.adam wrote:

you could add a before_create filter…

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 +=

So I’d be interested in how to do this as well.

Pat


#4

Larry W. wrote:

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

def initialize
@x = “default value”
end
end

MyModel.new.x # => “default value”
MyModel.find( 0 ).x # => “default value”

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.

Zach


#5

Hi !

2005/11/25, Larry W. removed_email_address@domain.invalid:

How do add initialization to a model class that adds an attribute and sets
its values? I tried adding an initialize method

Use the after_initialize callback. See my blog entry:
http://blog.teksol.info/articles/2005/12/14/setting-default-values-in-models

Bye !