I have three model:
- raw_coupon
- coupon
- store
If I’m looping through raw_coupons, how can I save it as a coupon only if the same coupon_code doesn’t already exist for that store? Here is code to make it more clear:
raw_coupon.each do |raw_coupon|
coupon = Coupon.new
coupon.store_id = raw_coupon.store_id
coupon.coupon_code = raw_coupon.coupon_code
coupon.save if [coupon_code for this store doesn't already exist]
end
How to I write out the [coupon_code for this store doesn’t already exist]
NOTE: more than one store can be using the same coupon code hence I need to check if the same coupon_code exists for that store specifically.
EDIT: Here are the model associations:
- raw_coupon: has_one :coupon
- coupon: belongs_to :raw_coupon && belongs_to:store
- store: has_many :coupons
Just add a unique validation to Coupon and watch out for errors when you call
coupon.save:The
:scopelimits the uniqueness check to the coupon codes for the coupon’sstore_id.You should also add a unique index to
couponson thestore_idandcoupon_codeas an extra layer of protection.