开发者

Can a Model constructor be empty in Rails?

开发者 https://www.devze.com 2022-12-19 05:09 出处:网络
I have a \'Cost\' model in rails.Something like the following: c开发者_JAVA技巧lass Cost < ActiveRecord::Base

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消