views:

210

answers:

3

I have a 'Cost' model in rails. Something like the following:

class Cost < ActiveRecord::Base

    belongs_to :cost_type
    has_many :cost_distributions

    attr_accessor :epp

    def initialize()
    end

However, in my tests, when I try to create new instance with the empty constructor

    cost = Cost.new

I get an error: wrong number of arguments (0 for 1). Why is it ignoring my empty constructor?

+2  A: 

You need to allow ActiveRecord to do its own initialization since you are essentially overriding the behavior. Just change your initialize to this:

def initialize()
 super
end

However, if you don't supply a constructor at all, Rails lets you create the model without parameters:

Cost.new

So is your empty initialize method doing anything else? If not, its not even needed.

Doug Neiner
That doesn't get rid of the error.
Daniel
If your `initialize` function is empty, and only contains 'super' then it should be working. I tested locally before posting to verify the solution, and it worked. I am pretty confident there is something else in your code (the part you didn't post) that is causing the error.
Doug Neiner
I have removed all methods from my Cost class and it seems that it still is expecting a initialize method with a parameter.
Daniel
Are you using nested_attributes? You *must* use initialize(*args) when you use nested attributes.
Mike
+1  A: 
def initialize(*args)
  super
end

Is the secret sauce.

Mike
A: 

In general, overriding ActiveRecord's initialize method isn't a very good idea.

If your initialize() does "nothing", you don't need it. Just remove it.

class Cost < ActiveRecord::Base

    belongs_to :cost_type
    has_many :cost_distributions

    attr_accessor :epp

end

You will still be able to invoke Cost.new (the right initialize method will be provided by ActiveRecord itself, if you don't override it).

egarcia