How to provide dummy values to a call to an optional polymorphic relationship in Ruby on Rails?

Viewed 62

If I have the following class

class Discount < ApplicationRecord
   belongs_to :coupon, polymorphic: true, optional: true

end

and have a situation where I would like to create a discount while leaving the coupon class nil, how can I provide values to client classes that call a line like

@discount.coupon.code

without having to add checks before the call? I would like to be able to specify the default values returned by calls like @discount.coupton.code based on the parameters in the Discount class.

Is there an easy way to do this in rails?

1 Answers

Should be able to override the getter. Something like this...

class Discount < ApplicationRecord
  belongs_to :coupon, polymorphic: true, optional: true

  def coupon
    unless some_condition
      self[:coupon]
    else
      OpenStruct.new(code: 'a_non_coupon_discount')
    end
  end
end
Related