Scholle
Scholle

Reputation: 1521

How to initialize ActiveRecord Model BEFORE form data gets processed by calling params[:model]?

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?

Upvotes: 0

Views: 2163

Answers (2)

valk
valk

Reputation: 9874

When you call super with no arguments it passes initialize's arguments to it. In order to properly initialize it use super():

 def initialize(*args)
  super()
  self.du = 1000
 end

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124419

If you want to initialize a model, and then pass attributes without re-initializing, you could do this:

@model = Model.new
@model.attributes = params[:model]

However, you may still run into a problem of it using the default value of du = 1000 when it hits your duration= and duration_day= methods depending on the order ActiveRecord parses your parameters.

Upvotes: 1

Related Questions