在类中重写关联的正确方法

时间:2017-06-24 19:16:12

标签: ruby-on-rails ruby

我正在尝试覆盖类实例上的关联。通常我想在ActiveRecord 中返回关联,除非满足某些逻辑。 见下文:

class Design < ActiveRecord::Base

belongs_to font

def font
  if override
    return another_font
  else
    # This results in a recursive call, stack level too deep.
    return send(:font)

    # This would work if font were an attribute, not an association
    return read_attribute(:font)
  end
end

有什么建议吗?感谢。

1 个答案:

答案 0 :(得分:2)

重写的方法可以调用super来调用原始方法:

def font
  if override
    another_font
  else
    super
  end
end

或更短:

def font
  override ? another_font : super
end