Assuming the following Model:
class Model < ActiveRecord::Base
def initialize(*args)
super
self.du = 1000
end
def duration=(val)
self.du = val
end
def duration_day
(du / (60 * 60 * 24)).floor
end
def duration_day=(val)
duration_tmp = duration_day - val
self.duration = duration_tmp
end
end
The attribute “du” gets persisted in the database. I want to initialize “du” when a new instance of Model is created in order to populate a form element called “duration_day”. This works so far.
However, when the form is submitted and the user provided value for “duration_day” is propagated to the new instance of Model by the controller as usual:
def create
@model = Model.new
@model = Model.new(params[:model])
end
…, I am getting a NoMethodError undefined method `/’ for nil:NilClass because attribute “du” has not been initialized at this time because “super” is called before the actual initialization. Removing “super” or moving it further down within the “initialize” method causes other errors.
Is there a chance to get this to work?
If you want to initialize a model, and then pass attributes without re-initializing, you could do this:
However, you may still run into a problem of it using the default value of
du = 1000when it hits yourduration=andduration_day=methods depending on the order ActiveRecord parses your parameters.