I have read allot of questions on here about different ways to initialize a ActiveRecord model properly when dealing with initializing values and is always in relation to providing default values. A great answer I came across helped clarify different ways.
However, if it is frowned upon to override the ActiveRecord base initialize method, what is the proper way to provide parameters to an ActiveRecord model when you want to initialize with values as you would in a standard Ruby class initialize(arg1, arg2...)
method.
so you can
obj = MyObject.new(Obj1, some_num)
The only thing I have come across was actually overrideing the initialize
method but calling super
first in the initialize. However, this was frowned on because ActiveRecord's base class uses allocate
in allot of cases to instantiate an AR object and therefore could end up sidestepping the entire initialize method.
So, maybe there is another fundamental reason why I am not finding providing initial values as a standard practice in RoR?
I know I can use validates in the object to validate an object can't be saved without meeting requirements, such as having all the proper attributes set. But I was approaching this particular object, so that it wouldn't be created without the required attributes when it is initialized to begin (since at initialization we would have all that information and if retrieving from the DB we would have all those values).
Can someone help direct me?
extra question If there is an accepted way to do the above, there seems to be another area that needs to be considered when initializing objects with values and that is when the object is initialized from being retrieved from the DB. Not handling the initializing values properly can possibly override what is retrieved from the DB (or I have read when related to setting attributes to default values). So if that needs to be handled properly, how do we do that?