Rails 即时添加到模型

Rails add to model on the fly

我有一个 belongs_to 场景的模型代理。两种模型都有字段 options,我想将 Scenario options 中存储的值与 Agent options 合并,这样我就可以 @agent.options 并从 AgentScenario.

中检索值

我试过了:

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

但这会引发 Stack too deep 错误。

如有任何建议,我们将不胜感激。谢谢!

因为 Agent 有一个名为 options 的字段 方法,当从 class 中调用 self.options 时,您调用方法而不是检索字段。当您尝试与 self.options 合并时,您将无限递归。重命名方法。

Brennan 已经解释过,您的 options 方法会重新调用自身,导致 Stack to deep 错误。

还有另一种(更底层的)方法来读取活动记录模型的属性:read_attribute。使用该方法,您可以编写:

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

这个方法正是为这个用例而存在的。详细了解 overwriting default accessors in the docs