Kosmonaut
Kosmonaut

Reputation: 2290

Rails 3 Custom Validation

I'm attempting to created a custom validation that verifies a schedule's start_date and end_date do not overlap with another schedule

class Schedule < ActiveRecord::Base
#has many scheduleTimes (fk in scheduleTime)
has_many :scheduletimes, :inverse_of => :schedule 

validate :dateOverlaps?

scope :active, lambda {
 where('? between start_date and end_date', Date.today)
}
def dateOverlaps?
  results = ActiveRecord::Base.connection.execute("Select (start_date::DATE, end_date::DATE) OVERLAPS ('#{self.start_date}'::DATE, '#{self.end_date}'::DATE) from schedules;")
  errors.add_to_base("Date ranges cannot overlap with another schedule") if                   results.first["overlaps"] == 't'
end

however, this causes

NoMethodError: undefined method `add_to_base' 

I have tried creating a custom validator and using the private validate method to no avail. Could someone shine some light on this for me?

Upvotes: 1

Views: 4576

Answers (2)

Matt Huggins
Matt Huggins

Reputation: 83279

Try replacing this:

errors.add_to_base("Date ranges cannot overlap with another schedule")

with this:

errors.add(:base, "Date ranges cannot overlap with another schedule")

Upvotes: 9

Chris
Chris

Reputation: 321

Instead of:

errors.add_to_base

try using:

errors.add

Upvotes: 1

Related Questions