views:

9

answers:

1

Hello all!

I've been using a model of my application as a proxy to other objects that define behavior.

  class Box < ActiveRecord::Base

  belongs_to :box_behavior, :polymorphic => true, :validate => true, :foreign_key => 'box_behavior_id', :dependent => :destroy

  [...]

  def initialize(opts = {})
    super(opts)
    self.box_behavior = BoxBehaviorDefault.new if self.box_behavior.blank?
  end

  private
    def method_missing(method, *args, &block)
      super
      rescue NoMethodError
        return self.box_behavior.send(method,*args,&block)
    end
end

So I implement all the methods on my BoxBehavior objects, and when I call a method on a box instance then it redirects the call to the associated boxbehavior object. It all works fine except when i tried to create a hook on my purchase model where it gets the total from its box object and saves it:

class Purchase < ActiveRecord::Base

  belongs_to :box

  before_validation_on_create { |r| r.total = r.box.total }
end

When I try to save any purchase object that has a box associated, I get this error:

undefined method `total' for #<ActiveRecord::Associations::BelongsToAssociation:0x7fe944320390>

And I don't have a clue on what to do next... When I implement the total method directly in the box class then it works fine... what can I do to solve this? Isn't the proxy working properly?

A: 

I found out that Rails doesn't always use initialize to create a new instance of a model. So i used the hook after_initialize and solved the problem!

Lucas d. Prim