Re: Calling a method on class creation

eggie5
Fri, 24 Aug 2007 19:04:18 -0000

THANKS! that''s the trick I was looking for. Now this reminds me of an
example from the essential rails book...

So, it looks like status is called automatically when a new instance
of the class is created?

On Aug 24, 5:37 am, Sava Chankov
<sava.chan...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> eggie5 wrote:
> > It doesn''t seem like the initializer gets called when you
create a new
> > instance using .find(), e.g.:
>
> > c=ContentCampaign.find(1)
> > c.status
>
> > => nill
>
> > However, If I create a new instance using new it works, e.g:
>
> > d=ContentCampaign.new
> > c.status
> > => Waiting
>
> > Here is my class, what''s going on?
>
> > class ContentCampaign < ActiveRecord::Base
> >   belongs_to :category, :class_name => "Category",
:foreign_key =>
> > "category_id"
>
> >   def initialize
> >    @status= evaluate_status
> >   end
>
> >   def evaluate_status
> >     ''Waiting''
> >   end
>
> >   def status
> >     @status
> >   end
>
> > end
>
> Try instead:
>
> class ContentCampaign < ActiveRecord::Base
>   belongs_to :category, :class_name => "Category",
:foreign_key
> =>"category_id"
>
>   def evaluate_status
>     ''Waiting''
>   end
>
>   def status
>     @status ||= evaluate_status