I have a 'Cost' model in rails. Something like the following:
c开发者_JAVA技巧lass 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?
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.
def initialize(*args)
super
end
Is the secret sauce.
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).
精彩评论