Bustikiller Bustikiller - 6 months ago 11
Ruby Question

Activerecord initialize attribute after mass_assign

I have a model inheriting

ActiveRecord::Base
with the following attributes in database:

scheduler.rb



# id :integer not null, primary key
# next_datetime :datetime
# first_datetime :datetime
# created_at :datetime not null
# updated_at :datetime not null


The objects in this model should be instantiated like this:

scheduler.new(first_datetime: DateTime.new(2016, 1, 1))


When the object is created (not necessarily saved to database), I would like to copy the attribute in
first_datetime
to
next_datetime
, so that I never get
nil
when I access
my_scheduler.next_datetime
.

I have tried to use
after_initialize
callback, but by the time this code is executed the mass assigned attributes are not available yet.

How can I get this attribute initialized? Any help would be appreciated.

Answer

The only thing I can think of is to override the initialize method of ActiveRecord::Base in such a way that you can add this little customization after the superclass of your model ends its processing.

That could be accomplished as follows:

def initialize(attributes = nil, options = {})
  super
  next_datetime ||= first_datetime
end

Hope this can help you!

Comments