Rails validate uniqueness only if conditional

后端 未结 3 740
Happy的楠姐
Happy的楠姐 2020-12-03 02:56

I have a Question class:

class Question < ActiveRecord::Base
  attr_accessible :user_id, :created_on

  validates_uniqueness_of :created_on, :scope =>          


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-03 03:16

    Just add a condition to the validates_uniqueness_of call.

    validates_uniqueness_of :created_on, scope: :user_id, unless: :has_posted?
    def has_posted
      exists.where(user_id: user_id).where("created_at >= ?", Time.zone.now.beginning_of_day)
    end
    

    But even better, just create a custom validation:

    validate :has_not_posted
    def has_not_posted
      posted = exists.where(user: user).where("DATE(created_at) = DATE(?)", Time.now)
      errors.add(:base, "Error message") if posted
    end
    

提交回复
热议问题