Search code examples
rubyvalidationdatetimeruby-on-rails-4.2model-validation

Uniqueness validation on datetime field with scope


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!!


Solution

  • 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}