Monday, October 19, 2009

Error using validation hooks with before_save callback


# This will throw "Schedule can't be blank" error as any changes made in before_save callback somehow gets lost
class Assessment < ActiveRecord
validates_presence_of :schedule

attr_accessor :date, :time
before_save :set_schedule_from_date_and_time

private

def set_schedule_from_date_and_time
if self.date && self.time
self.schedule = Time.parse("#{date} #{time}")
end
end

# The trick is to use before_validation
before_validation :set_schedule_from_date_and_time

No comments:

Blog Archive