Overriding initialize in active_record Model or after_initialize


I am trying to set initial process when instantiating model by
overriding initialize() method which takes arguments. The initialize()
method overrides the parent ActiveRecord::Base class’s by taking
arguments and assign arguments to its instance variables.

class Product < ActiveRecord::Base

def initialize(item = nil)
# and then process to assign variables from item argument to
instance variables
# …

In order to fully leverage ActiveRecord::Base class functionality, I’m
calling super to run the default initialization process (i.e. set up
all setter/getter methods). However, the Product class above still
can’t find getter/setter methods for its variables. In the meantime, I
found the following blog article suggesting use after_initialize
instead of overriding Active Record object.

Rails: Don’t override initialize on ActiveRecord objects

I could not find ways to set arguments for this after_initialize

Can anybody advise should I override initialize() or use
after_initialize with some ways to take arguments?


On Nov 8, 8:04 am, Ryoichiro K. [email protected]

 # and then process to assign variables from item argument to  

instance variables
# …

What does the actual code in there look like? What is the error that
you get ?


Thanks Fred.

I got the following error.
NoMethodError in ProductsController#search
undefined method stringify_keys!' for #<Amazon::Element:0x10373c6a8> /Library/User/Gems/1.8/gems/activerecord-2.3.3/lib/active_record/ base.rb:2731:inattributes=’
base.rb:2434:in initialize' /Users/User/Documents/Aptana Studio Workspace/Flatworld/app/models/ product.rb:5:ininitialize’
/Users/User/Documents/Aptana Studio Workspace/Flatworld/app/models/
products.rb:31:in `new’
… [more]

and actual code for the model class is:

class Product < ActiveRecord::Base
has_many :inventories

def initialize(item)
@amazon_asin = item.get(‘asin’)
@manufacturer = item.get(‘itemattributes/manufacturer’)
@name = item.get(‘itemattributes/title’)
@releasedate = item.get(‘itemattributes/releasedate’)
@amazon_url = item.get(‘detailpageurl’)
@amazon_image = item.get_hash(‘smallimage’)

item is the result from Amazon API search result. I am trying to
instantiate Product class with the result data set.
Is this right approach to instantiate model class by overriding
initialize method with super method within?