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 type
to 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 DiscountedCoupon
record.
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?
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