日期的自定义验证

时间:2013-01-25 16:43:59

标签: ruby-on-rails-3

我正在尝试创建一个自定义验证,用于评估创建记录所需的日期是否可用。

这是我的表计划架构

  create_table "schedules", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.integer  "doctor_id"
    t.boolean  "sun"
    t.boolean  "mon"
    t.boolean  "tue"
    t.boolean  "wed"
    t.boolean  "thu"
    t.boolean  "fri"
    t.boolean  "sat"
  end

e.g。如果请求的日期是星期五并且schedule.fri为真,则可以创建记录,否则会引发错误。

有没有办法迭代表计划的数据字段来评估哪些天返回true或false所以我可以将它与请求的日期进行比较?

1 个答案:

答案 0 :(得分:0)

我想你可能正在寻找这样的东西。假设您正在尝试验证Appointment模型,则验证可能类似于:

class Appointment
  # this assumes that the appointment has at least two fields:
  # doctor_id : the same value as in the Schedule object
  # adate : a string in the form "mon", "tue", etc.
  validate :doctor_is_free
  def doctor_is_free 
    schedule = Schedule.where(doctor_id: self.doctor_id).first
    #return the day of a date. e.g. "sun"
    requested_day = adate.to_date.strftime("%a").downcase

    # this line will send a request to the Schedule instance using
    # the value of adate as the method name. So if adate == 'tue' and
    # schedule.tue = false then this will add an error to the validation.
    unless schedule.send(requested_day.to_sym)
      self.errors[:adate] << "The doctor is not available on #{ self.adate }"
    end
  end
end