Adam
Adam

Reputation: 683

Rails add to model on the fly

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!

Upvotes: 2

Views: 339

Answers (2)

spickermann
spickermann

Reputation: 106922

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.

Upvotes: 4

Brennan
Brennan

Reputation: 5742

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.

Upvotes: 2

Related Questions