简体   繁体   English

如何写此活动记录? (Rails 3.1)

[英]How can I write this active record? (Rails 3.1)

I have three model: 我有三种模式:

  • raw_coupon 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? 如果我要遍历raw_coupons,那么仅当该商店尚不存在相同的coupon_code时,如何才能将其另存为优惠券? 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. 注意:多个商店可以使用相同的优惠券代码,因此我需要检查该商店是否专门存在相同的coupon_code。

EDIT: Here are the model associations: 编辑:这是模型关联:

  • raw_coupon: has_one :coupon raw_coupon:has_one:优惠券
  • coupon: belongs_to :raw_coupon && belongs_to:store 优待券:belongs_to:raw_coupon &&归属地:store
  • store: has_many :coupons 商店:has_many:优惠券

Just add a unique validation to Coupon and watch out for errors when you call coupon.save : 只需向Coupon添加唯一的验证,并在致电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 . :scope将唯一性检查限制为优惠券的store_id的优惠券代码。

You should also add a unique index to coupons on the store_id and coupon_code as an extra layer of protection. 您还应该在store_idcoupon_code上的coupons上添加唯一索引,作为额外的保护层。

you can use find_or_initialize_by helper. 您可以使用helper的find_or_initialize_。 I wouldnt recommend find_or_create_by helper since it wont raise error if validations fail on create. 我不会推荐find_or_create_by帮助程序,因为如果在创建时验证失败,它不会引发错误。

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 仅供参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM