bsky
bsky

Reputation: 20242

Rails - initialize object instance variable

I have two arrays which I would like to initialise to [] in my Prediction model's object.

If I try:

def initialize
    @first_estimation = []
    @last_estimation = []
end

Then many of my unit tests fail.

 Failure/Error: assign(:prediction, Prediction.new(
     ArgumentError:
       wrong number of arguments (1 for 0)

However, if I try:

def after_initialize
    @first_estimation = []
    @last_estimation = []
end

Then the arrays do not get instantiated.

How can I instantiate the arrays when the object is constructed without altering anything else?

Upvotes: 1

Views: 63

Answers (1)

apneadiving
apneadiving

Reputation: 115541

Since I see a parenthesis here Prediction.new( I deduce you try to pass params.

But your initialize doesnt accept any => boom


But wait, is it an ActiveRecord model?

If so, you have to use:

 after_initialize :set_arrays

 def set_arrays
   @first_estimation = []
   @last_estimation = []
 end

and maybe use attr_accessor too, but dont know what you expect

Upvotes: 5

Related Questions