0

My main model:

class Coupon < ActiveRecord::Base
  include Concerns::CouponDistribution
end

The related Concern class:

module Concerns::CouponDistribution
  extend ActiveSupport::Concern

  included do
    after_create :create_coupons_for_existing_users
  end

  def create_coupons_for_existing_users
    #
  end

end

Now I have a child model 'discounted_coupon.rb' which inherits from the coupon model:

class DiscountedCoupon < Coupon

end

I have added a column typeto my main model as per STI requirements: http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html

My goal:

I want to ignore the Concern "CouponDistribution" if I create a new DiscountedCouponrecord.

So I wrote this in my Concern:

after_create :create_coupons_for_existing_users unless self.type == "DiscountedCoupon"

plots an error:

undefined method `type' for #

Is there any other way to achieve my goal? E.g. explicitly skip/ignore the Concern in my child model?

DonMB
  • 2,550
  • 3
  • 28
  • 59

2 Answers2

1

There might be two ways of doing it. One is a simpler way:

def create_coupons_for_existing_users
  return unless self.type == "DiscountedCoupon"
  # your logic here
end

And the other one is like:

after_create : create_coupons_for_existing_users, unless: :discounted_coupon?

In your model you can write the method discounted_coupon?

def discounted_coupon?
  self.type == "DiscountedCoupon"
end 
usmanali
  • 2,028
  • 2
  • 27
  • 38
1

You can try it

module Concerns::CouponDistribution
  extend ActiveSupport::Concern

  included do
    after_create :create_coupons_for_existing_users, if: Proc.new {|cd| cd.type == "DiscountedCoupon" }
  end

  def create_coupons_for_existing_users
    #
  end

end
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74