2

我似乎不時遇到此問題,當我想驗證一個字段,並將其範圍限制爲特定日期時,我正在存儲日期時間。validates_uniqueness_of與日期時間

validates_uniqueness_of :user_id, scope: [:starts_at, :state] 

問題是starts_at存儲爲datetime,但我不希望驗證的確切時間,而是一般的日期。

當我遇到這個問題時,我通常會創建一個自定義驗證方法,並且有時在有時間窗口時有意義,但是我想知道如果我只關心整個日期,我是否忽略了更好的解決方案。

我想避免創建像下面的自定義驗證,如果有另一種可能性。

老辦法

def check_user_uniqueness 
    if EventLog.where("start_at::date = ? AND id <> ? AND user_id = ?", 
    start_at.to_date, id, user_id).count > 0 
    errors.add(:user_id, "isn't available on this date") 
    end 
end 

感謝

+0

我只能想到一個**自定義驗證**。如果'starts_at'是一個**日期(不是日期時間)**,那麼它可以通過'validates_uniqueness_of'實現。 – Pavan

回答

1

這是很合理的,爲此創建自定義的驗證,但你可以很喜歡使用exists?,而不是count/> 0檢查,這是更具可讀性和不正是你需要的:

def check_user_uniqueness 
    if EventLog.where(id: id, user_id: user_id).exists?("start_at::date = ?", start_at.to_date) 
    errors.add(:user_id, "isn't available on this date") 
    end 
end