1

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?

Community
  • 1
  • 1
pghtech
  • 3,642
  • 11
  • 48
  • 73

1 Answers1

-1

You can provide a hash of values when you initialize an ActiveRecord object. This is used in the create action of the controller to create a new object based on the data collected in the new action.

For example:

def create
  @book = Book.new(params[:book])

where params is a hash of the values for the new object.

Richard Brown
  • 11,346
  • 4
  • 32
  • 43
  • 1
    Richard Brown thanks - But this also allows for @book = Book.new which is what I am trying to figure out how to make not happen without raising an error - which is what my question is all about. – pghtech Mar 22 '13 at 12:32