Re: Calling a method on class creation

Sava Chankov
Fri, 24 Aug 2007 12:37:07 -0000

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