I have three model:
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:
Just add a unique validation to Coupon and watch out for errors when you call coupon.save
:
class Coupon < ActiveRecord::Base
validates :coupon_code, :uniqueness => { :scope => :store_id }
#...
end
The :scope
limits the uniqueness check to the coupon codes for the coupon's store_id
.
You should also add a unique index to coupons
on the store_id
and coupon_code
as an extra layer of protection.
you can use find_or_initialize_by helper. I wouldnt recommend find_or_create_by helper since it wont raise error if validations fail on create.
raw_coupon.each do |raw_coupon|
coupon = Coupon.find_or_initialize_by_store_id_and_coupon_code(raw_coupon.store_id, raw_coupon.coupon_code)
coupon.save! if coupon.new_record? #This just saves you from extra DB calls.
end
i used save! to raise an exception if your validation fails. Just FYI
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.