Uniqueness validation on datetime field with scope

508 views Asked by At

This is my model file.

class Attendance < ActiveRecord::Base
belongs_to :staff, class_name: 'User', foreign_key: 'staff_id', inverse_of: :attendances
belongs_to :child, inverse_of: :attendances

validates :attendance_date, uniqueness: {scope: :child} 

end

my main goal is to not allow the same date and child_id to be saved in database.The validation which i wrote is not working in this scenario.

The attendance_date is a datetime field.

please help me solve this issue!!

1

There are 1 answers

0
Pardeep Dhingra On BEST ANSWER

Validate uniqueness with scope is to add multiple column constraint for the uniqueness. You can add column's you want to use for applying uniqueness:

Try this:

validates :attendance_date, uniqueness: {scope: :child_id}