views:

53

answers:

1

I have a new app (Rails 2.3.8) that uses lots of money fields. I'm using the money gem (3.0.5) and the acts_as_money plugin. I've written a number of rspec model examples and everything seems to be working fine there.

My problem is in defining forms for new & edit. As I've done in past projects for complex layouts, I extracted the basic form to a partial and include it in the new & edit views.

However, the model object is created and left with nulls in the fields, and causes the money gem to complain with: "undefined method `subunit_to_unit' for nil:NilClass".

I thought I could use something like after_initialize() to hook into the creation of a new object in Rails and set all the money attributes to zero, but that didn't work (and several posts recommended against that for performance reasons)...

Any suggestions on a clean way to hook my model object and make sure it's got zeros for all the money values?

A: 

after_initialize does not do what you think it does

the way too hook into init is as follows:

class MyModel < ActiveRecord::Base

  def initialize(*args, &block)
     super         # no () form is equivalent to super(*args, &block)
     set_defaults
  end

  private

  def set_defaults
    # Do your defaults here
  end

end
glebm