擁有屬於某個類別的產品。想要在短時間內創建促銷活動(可以說是一週或兩週),但在此期間,它們只能針對每個類別進行一次促銷。Ruby複製驗證
如何爲此創建自定義驗證?
product class
belongs_to :categories
name:string
desc:text
reg_price:decimal
category_id:integer
promo_active:boolean
promo_price:decimal
promo_start:datetime
promo_end:datetime
end
category class
has_many :products
name:string
end
更新到可能的解決方案?
class Product < ActiveRecord::Base
attr_accessible :name, :desc, :reg_price, :category_id, :promo_active, :promo_price, :promo_start, :promo_end
belongs_to :category
#validate :check_unique_promo
#Tweaked original to be more exact and
#Give clue if its the start or end date with the error.
validate :check_unique_promo_start
validate :check_unique_promo_end
def check_unique_promo
errors.add_to_base("Only 1 promo allowed") unless Product.count(:conditions => ["promo_active = ? AND promo_end < ?", true, self.promo_start]) == 0
end
def check_unique_promo_start
errors.add_to_base("Start date overlaps with another promotion.") unless self.promo_active == false || Product.count(:conditions => ['promo_end BETWEEN ? AND ? AND category_id = ? AND promo_active = ? AND id != ?',self.promo_start, self.promo_end, self.category_id, true, self.id]) == 0
end
def check_unique_promo_end
errors.add_to_base("End date overlaps with another promotion.") unless self.promo_active == false || Product.count(:conditions => ['promo_start BETWEEN ? AND ? AND category_id = ? AND promo_active = ? AND id != ?',self.promo_start, self.promo_end, self.category_id, true, self.id]) == 0
end
end
我跳過自我,如果promo_active錯誤的表現。
如此做更新的代碼工作? – 2010-05-09 15:04:35
似乎。現在測試。看起來就像我把它歸結爲min,但用日期做數據庫查詢並不有趣,似乎給我帶來了很多與時區有關的問題。看到你的代碼如何導致答案,我將其標記爲正確。 – pcasa 2010-05-09 15:08:29