mdundas
mdundas

Reputation: 799

Proper way to override an Association in a class

I'm trying to override an association on a class instance. Usually i want to return the association in ActiveRecord unless certain logic is met. See below:

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

Any suggestions? Thanks.

Upvotes: 1

Views: 365

Answers (1)

spickermann
spickermann

Reputation: 107087

Overridden methods can call super to call the original method:

def font
  if override
    another_font
  else
    super
  end
end

Or shorter:

def font
  override ? another_font : super
end

Upvotes: 2

Related Questions