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.
on 2005-11-25 19:12
on 2005-11-25 19:52
you could add a before_create filter....
on 2005-12-14 12:41
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
on 2005-12-14 14:14
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
on 2005-12-14 17:57
Hi ! 2005/11/25, Larry W. <email@example.com>: > 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/settin... Bye !