Adding custom attributes to an ActiveRecord object

Subject line states the question. I’m adding the following to an
ActiveRecord class:

class Institution < ActiveRecord::Base

list of associations

has_and_belongs_to_many(:license_types)

attr_accessor :tmp_license_types

public
def initialize(attributes = nil)
super(attributes)
@tmp_license_types = Array.new
self.license_types.each { |lt| self.tmp_license_types << lt }
end

The problem is that if I try to access this attribute in my controller I
keep
getting a nil object error. Also, I tried calling

<%= debug(@institution) %>

in my view an this extra attribute that I added is not being reported.
Any ideas?

Thanks,
Steven

Re: Adding Additional Attributes to ActiveRecord?

I found the answer to my question, and will post it here in case anyone
else has this problem.
Overiding the initialize() function can cause problems with
ActiveRecord.

You should instead define
Code:
def after_initialize

stuff

end

-Steven

I am having this problem. I wanted to write a custom initializer that
takes some arguments, but of course, everything puked. I thought this
would work:

class Foo < AcitveRecord::Base
initialize(some_arg)
super
@my_var1 = somer_arg.something
@my_var2 = somer_arg.something_els
end
end

Why doesn’t the call to super() make sure that all the ActiveRecord
initialization is correctly setup? I like the after_initialize_trick,
although it doesn’t fix my problem; instead I’ve created a factory
method self.build_new_foo(some_args).

  • Doug

rooster wrote:

Re: Adding Additional Attributes to ActiveRecord?

I found the answer to my question, and will post it here in case anyone
else has this problem.
Overiding the initialize() function can cause problems with
ActiveRecord.

You should instead define
Code:
def after_initialize

stuff

end

-Steven

I believe the ActiveRecord initialize method is expecting an
argument…check source from svn. Anyway, if you’re going to
overide initialize and you want to make sure everything gets setup
right, do:

def initialize(attributes = nil)
super(attributes)
end

Douglas De Couto wrote:

I am having this problem. I wanted to write a custom initializer that
takes some arguments, but of course, everything puked. I thought this
would work:

class Foo < AcitveRecord::Base
initialize(some_arg)
super
@my_var1 = somer_arg.something
@my_var2 = somer_arg.something_els
end
end

Why doesn’t the call to super() make sure that all the ActiveRecord
initialization is correctly setup? I like the after_initialize_trick,
although it doesn’t fix my problem; instead I’ve created a factory
method self.build_new_foo(some_args).

  • Doug

rooster wrote:

Re: Adding Additional Attributes to ActiveRecord?

I found the answer to my question, and will post it here in case anyone
else has this problem.
Overiding the initialize() function can cause problems with
ActiveRecord.

You should instead define
Code:
def after_initialize

stuff

end

-Steven