2

I have a model Agent that belongs_to Scenario. Both models have the field options and I would like to merge the values stored in Scenario options with Agent options so that I can do @agent.options and retrieve the values from both Agent and Scenario.

I tried:

# in agent.rb
def options
  scenario.options.merge(self.options)
end

But this throws a Stack too deep error.

Any suggestions would be greatly appreciated. Thanks!

Adam
  • 673
  • 1
  • 8
  • 18

2 Answers2

4

Brennan already explained that your options methods resursively calls itself what leads to the Stack to deep error.

There is an other (more low level) way to read an attribute of an active record model: read_attribute. Using that method you can write:

def options
  read_attribute(:options).merge(scenario.options)
end

This method exist exactly for this usecase. Read more about overwriting default accessors in the docs.

spickermann
  • 100,941
  • 9
  • 101
  • 131
2

Because Agent has a field and method named options, when calling self.options from within the class you call the method instead of retrieving the field. When you try to merge with self.options, you are recursing infinitely. Rename the method.

Brennan
  • 5,632
  • 2
  • 17
  • 24
  • 1
    Thanks for your response. I had named the method the same as the field with the hope that I could override the call to `@agent.options` so that I can keep existing references to `@agent.options`. Is there a good way to merge the two options hashes on the fly so I can still call `options` but get both? I'm thinking the best way may be to merge the two in an `after_initialize` callback. – Adam Feb 06 '15 at 21:37